<?php 
/**
This is Norman's Change 

 */
class StaffController extends Zend_Controller_Action
{

    public function init(){
    /**
	 *
	 *
	 */    
	//Test
	}

    public function indexAction(){
	
		//echo "Watch Dog Controller";	

    
	}
	
	/**
	 * Mannual add shop bonus 
	 * Modifyed By Norman on 07-14 Add TYpe 
	 */
	public function addShopBonusAction(){
	
		$codeShop = $this->_getParam("shop");
		$shopList = unserialize(ARR_SHOP_GROUP);
		
		
		//$idShop = $this->_getParam("shop");
		$periodBegin = "";
		$periodEnd = "";
		$payDate = "";
		//$payType = 1;
	
		$periodBegin = $this->_getParam("date_begin");
		$periodEnd = $this->_getParam("date_end");
		$payDate = $this->_getParam("pay_date");
		//$payType = $this->_getParam("pay_type");
		$type = $this->_getParam("type");
		$this->view->type = $type;
		$this->view->codeShop = $codeShop;
	
			
		$this->view->periodBegin = $periodBegin;
		$this->view->periodEnd = $periodEnd;
		$this->view->payDate = $payDate;
		//$this->view->payType = $payType;
	
	
	
		$bType = new Model_Payroll_Staffbonustype();//Staffbounstype ??
		//$stInfo = new Model_DbTable_Roster_Staffinfo();//Staffinfo ??
		$bos = new Model_Payroll_Shopgroupbonus();
		$shInfo = new Model_Payroll_Shopgroup();
		$myId = $shInfo->getShopid($codeShop);
		
		$idShop = $myId['id_group'];
	
		$stRow = $shInfo->getShopgroup($idShop);
		$this->view->stDetail = $stRow;
		$this->view->bTypeList = $bType->listAll();
		
		if(isset($_POST['button'])){
			//var_dump($_POST);
			if($_POST['bonus_type'] == 1 || $_POST['bonus_type'] == 2 || $_POST['bonus_type'] == 3){
				$payDate = (trim($_POST['hold_to_date'])=='')?$_POST['pay_date']:$_POST['hold_to_date'];
				$bos->newShopbonus($idShop, $_POST['bonus_type'], $_POST['detail_bonus'],$_POST['amt_total'],$_POST['amt_cash'], $_POST['amt_bank'], $_POST['amt_super'], $_POST['period_begin'], $_POST['period_end'], $payDate, $_POST['pay_type'], $_POST['hold_to_date'],$_POST['hold_reason'],$codeShop);
				echo "For Shop ID: ".$idShop."Name: ".$codeShop." Bonus Added Success";
			}else{
				$payDate = (trim($_POST['hold_to_date'])=='')?$_POST['pay_date']:$_POST['hold_to_date'];
				$bos->newShopbonus($_POST['shop_code'], $_POST['bonus_type'], $_POST['detail_bonus'],$_POST['amt_total'],$_POST['amt_cash'], $_POST['amt_bank'], $_POST['amt_super'], $_POST['period_begin'], $_POST['period_end'], $payDate, $_POST['pay_type'], $_POST['hold_to_date'],$_POST['hold_reason'],$shopList[$_POST['shop_code']]);
				echo "For Shop ID: ".$_POST['shop_code']."Name: ".$shopList[$_POST['shop_code']]." Bonus Added Success";
			}
		}
	}
	
	/**
	 * This function is for add other lost for shop
	 * will auto deduct from team bonus
	 @author leo
	 */
	public function addOtherLostAction(){
		$shopgroup = unserialize(ARR_SHOP_GROUP);
		$shopLost = new Model_Payroll_Shopgroupbonus();
		$sDetail = new Model_DbTable_Roster_Stafflogindetail();
		$cycle = unserialize(BONUS_CYCLE_2015);
		$otherLost = array();
		
		if(isset($_POST['submit'])){
			$amount = $_POST['amount'];
			$note = $_POST['note'];
			$cycleKey = $_POST['cycle'];
			$shopKey = $_POST['shopgroup'];
			$password = $_POST['password'];
			$idStaffRow = $sDetail->checkPasswordCorrect(Model_EncryptHelper::hashsha(trim($password)));
			
			if($idStaffRow){

				$shopLost->newShopbonus($shopKey, 10, $note, $amount, $amount, 0, 0, $cycle[$cycleKey][0], $cycle[$cycleKey][1], '1111-11-11', 0, '1111-11-11', 'none',$shopgroup[$shopKey],$idStaffRow['ni']);
	
			}else{
				echo '<script>alert("Wrong Password!!");</script>';
				return false;
			}
			$url = "/staff/add-other-lost";
			$this->_redirect($url);
			$this->view->addsuccess = "Add success";
		}
		
		if(isset($_POST['delect'])){
			$id = key($_POST['delect']);
			$shopLost->deleteShopbonus($id);
			$url = "/staff/add-other-lost";
			$this->_redirect($url);
		}
		
		if(isset($_POST['confirm'])){
			$idStaffRow = $sDetail->checkPasswordCorrect(Model_EncryptHelper::hashsha($_POST['pcode'][key($_POST['confirm'])]));
			if($idStaffRow['id'] == 431){
		
				$id = key($_POST['confirm']);
				$shopLost->updateHoldReason($id);
				$url = "/staff/add-other-lost";
				$this->_redirect($url);
			
			}else{
				echo '<script>alert("You do not have autherization!!");</script>';
			}
		}
		
		$summaryLost = $shopLost->getAllOtherLost();
		$this->view->summaryLost = $summaryLost;
		$this->view->shopgroup = $shopgroup;
	}
	
	/**
	 * This function is for add staff other lost
	 * @version Leo
	 */
	public function addStaffOtherLostAction(){
		$deductLog = new Model_Payroll_Staffdeductlog();
		$sDetail = new Model_DbTable_Roster_Stafflogindetail();
		$pr = new Model_DbTable_Pr_Prproducts();
		
		$tmplogList = $deductLog->listAll();
		$logList = array();
		$error = false;
		foreach ($tmplogList as $k => $v){
			$logList[$v['staff_id']][] = $v; 
		}
		
		$this->view->logList = $logList;
		
		if(isset($_POST['submit_deduct'])){
			$barcode = strtoupper($_POST['barcode']);
			$note = $_POST['note'];
			$password = $_POST['password'];
			$stfId = $_POST['staff'];
			$logDate = Model_DatetimeHelper::dateToday();
			if(!empty($stfId)){
				$idStaffRow = $sDetail->checkPasswordCorrect(Model_EncryptHelper::hashsha(trim($password)));
					
				if($idStaffRow){
					$pDetail = $pr->getProductByCode($barcode);
					if($pDetail && $pDetail['price_q'] > 0 && !empty($pDetail['price_q'])){
						$amount = round($pDetail['price_q'] * -0.9,2);
						$deductLog->addDeduct($stfId, $amount, $logDate, $note, $idStaffRow['ni']);
					}else{
						$error = true;
						$this->view->addsuccess = "No Bottom Price";
					}
					
				}else{
					$error = true;
					$this->view->addsuccess = "Wrong Password";
				}
				$this->renderScript('/staff/add-staff-other-lost.phtml');
			
				
			}
			
			if($error == false){
				$url = "/staff/add-staff-other-lost";
				$this->_redirect($url);
			}
		}
		
	}
	
	//FIXME: what is this
	public function getShopBonusDetailAction(){
		
		$idBonus = $this->_getParam("id_bonus");

		$shopBonus = new Model_Payroll_Shopgroupbonus();
		
		$bList = $shopBonus->getShopbonus($idBonus);
		
		$this->view->bList = $bList;
		
		
	}
	
	/**
	 * For team bouns wizard start page
	 * @version 2014-08-19
	 * @author Leo
	 */
	public function teamBonusWizardAction(){
		$bonuscycle = unserialize(BONUS_CYCLE_2015);
		$this->view->cycle = $bonuscycle;
		
		if(isset($_POST['next'])){
			$cycle = explode(':', $_POST['cycle']);
			foreach($bonuscycle as $k => $v){
				if($cycle[0]== $v[0] && $cycle[1] == $v[1]){
					$mycycle = $k + 1;
				}
			}
			
			$url = "/staff/team-bonus-wizard-add-bonus/date_begin/".$cycle[0]."/date_end/".$cycle[1]."/cycle/".$mycycle."/next/yes";
			$this->_redirect($url);
		}
		if(isset($_POST['jump'])){
				
			$url = "/staff/team-bonus-wizard-all-summary/";
			$this->_redirect($url);
		}
	}
	
	/**
	 * This function is for add team target/hit target
	 * and send target to manger by email, confirm target before calculate bonus 
	 * @version 2014-08-19
	 * @author Leo
	 */
	public function teamBonusWizardAddBonusAction(){
					
		$wTar = new Model_DbTable_Target_Weeklytarget();
		$managerMail = unserialize(ARR_MANAGER_EMAIL);
		//$wTlist = $wTar->listAll();
		//$this->view->wtList = $wTlist;
		$dateStart = $this->_getParam("date_begin");
		$dateFinish = $this->_getParam("date_end");
		$nextCheck = $this->_getParam("next");
		$cycle = $this->_getParam("cycle");
		
		if($nextCheck == 'yes'){
			$check = true;
			$this->view->nextCheck = $check;
		}
		
		$rTarget = $wTar->getWeeklytargetByShop($dateStart,$dateFinish);
		$this->view->rTarget = $rTarget;
		
		if(isset($_POST['upload'])){
				$file = $_FILES['upload_file']['tmp_name'];
				if(empty ($file)){
					$this->view->errorFlag2 = true;
						
					$this->view->errorMessage = "Please import the file";
					$this->renderScript('/products/importCsv.phtml');
					return false;
				}

				$arrResult = array();
					
				$fl = fopen($file,"r");
					
				while(($lineData = fgetcsv($fl,0)) != false){
						
					$arrResult[] = $lineData;
				}
			
				fclose($fl);
				array_shift($arrResult);
				if($arrResult[0][1]== $cycle){
					$this->view->targetList = $arrResult;
				}else{
					echo '<script>alert("Wrong Cycle!!");</script>';
				}
		}
		
		if(isset($_POST['sendMail'])){
			$rTarget = $wTar->getWeeklytargetByShop($dateStart,$dateFinish);
			$shopFomula = new Model_DbTable_Target_Shopfomula();
			$managerList = $shopFomula->listAll();
			$mail = new Model_Emailshandler();
			$email = array();
			foreach ($managerList as $k => $v){
				if(array_key_exists($v['shop_code'], $rTarget)){
					$email[$v['id_staff']][$v['shop_code']] = $rTarget[$v['shop_code']]; 
				}
			}
			
			foreach ($email as $manager => $value){
				 $title = "Shop Target from ".$dateStart." - ".$dateFinish;
				 $str = "";
				 foreach ($value as $shop => $weekT){
				 	$str .= "Shop:".$shop."  Period:".$dateStart." - ".$dateFinish."<br/>"."Target1:".$weekT['target']."<br/>"."Target2:".$weekT['target2']."<br/>"."Target3:".$weekT['target3']."<br/><br/>";
				 }
				 $str .= "If you have any problem, Please call headOffice.";
				 $mail->sendNormalEmail($managerMail[$manager], $title, $str);
			}
			
			echo "Email Sent Successful";
			
			
			
		}
		

		if(isset($_POST['button'])){
			//echo
			if($_POST["password"]=="Office051788"){
				
				$dateBegin = $_POST['date_begin'];
				$dateEnd = $_POST['date_end'];
				$actDateBegin = $dateBegin;
				$actDateEnd = Model_DatetimeHelper::adjustDays("add", $actDateBegin,6);
				
				$count = 0;
				while($actDateEnd <= $dateEnd){
					$target = $_POST['target'];
					$target2 = $_POST['target2'];
					$target3 = $_POST['target3'];
					$htarget = $_POST['htarget'];
					$htarget2 = $_POST['htarget2'];
					$htarget3 = $_POST['htarget3'];
					foreach($_POST['shop_code'] as $key => $v){
						$wTar->addWeeklytarget($v, $actDateBegin, $actDateEnd, $target[$key], $target2[$key], $target3[$key],$htarget[$key],$htarget2[$key],$htarget3[$key]);
					}
					$count ++;
					$actDateBegin = Model_DatetimeHelper::adjustWeeks("add", $actDateBegin,1);
					$actDateEnd = Model_DatetimeHelper::adjustWeeks("add", $actDateEnd,1);

				}
				echo "Upload success";
				//$this->_redirect("/shops/input-target");
			}
			else{
		
				echo "Password Incorrect";
			}
		}
		$this->view->cycle = $cycle;
		$this->view->dateStart = $dateStart;
		$this->view->dateEnd = $dateFinish;
		
	}
	
	
	/**
	 * This function is for calculate pure bonus
	 * compare sale and target 
	 * @version 2014-08-19
	 * @author Leo
	 */
	public function teamBonusWizardCalBonusAction(){
		error_reporting(E_ALL ^ E_NOTICE);
		$bonusRecord = new Model_Payroll_Shopgroupbonusrecord();
		$shopArr = unserialize(ARR_SHOP_ACTIVE);
		$bonuscycle = unserialize(BONUS_CYCLE_2015);
		$target = new Model_DbTable_Target_Weeklytarget();
		$cashAccount = new Model_DbTable_Cashaccount_Remote_Closing();
		$targetList = array();
		$shopList = array();
	
		
		$nextCheck = $this->_getParam("next");
		
		if($nextCheck == 'yes'){
			$check = true;
			$this->view->nextCheck = $check;
		}
		
		
		$dateBegin = $this->_getParam("date_begin");
		$dateEnd = $this->_getParam("date_end");
		$this->view->dateStart = $dateBegin;
		$this->view->dateEnd = $dateEnd;
		$nextCycleBegin = "";
		$nextCycleEnd = "";
		$cycleKey = 0;
		
		foreach($bonuscycle as $kc => $vc){
				
			if($dateBegin >= $vc[0] && $dateEnd <= $vc[1] ){
				$cycleKey = $kc + 1;
			}
		}
		$this->view->cycle = $cycleKey;
		
		$tmpArr = array();
		
		foreach($shopArr as $k => $v){
			$startDate = $dateBegin;
			$cashTotal = 0;
			$count = 0;
			
			$shopTarget = $target->getWeeklyTargetByShopByDate($v, $dateBegin);
			if(!empty($shopTarget)){
				if($shopTarget['shop_code'] == 'CLPC' || $shopTarget['shop_code'] == 'ADPC' || $shopTarget['shop_code'] == 'WLIC'){	
				
				if($shopTarget['shop_code'] == 'BSIC' || $shopTarget['shop_code'] == 'BSPC' || $shopTarget['shop_code'] == 'BSXP'){
				
				$tmpArr['BS_GROUP']['target1'] += $shopTarget['target'];
				$tmpArr['BS_GROUP']['target2'] += $shopTarget['target2'];
				$tmpArr['BS_GROUP']['target3'] += $shopTarget['target3'];
				$tmpArr['BS_GROUP']['htarget1'] += $shopTarget['htarget'];
				$tmpArr['BS_GROUP']['htarget2'] += $shopTarget['htarget2'];
				$tmpArr['BS_GROUP']['htarget3'] += $shopTarget['htarget3'];
				
				while($startDate <= $dateEnd){
					$cash = $cashAccount->getActiveClosingByDate($v, $startDate,$startDate);
					$startDate = Model_DatetimeHelper::adjustDays('add', $startDate, 1);
					if($cash != null){
						$cashTotal += $cash[0]['apos_sys_sales_total'];
					}	
				}
				$tmpArr['BS_GROUP']['total_sale'] += $cashTotal;
				
				$tmpArr3[$v]['target1'] = $shopTarget['target'];
				$tmpArr3[$v]['target2'] = $shopTarget['target2'];
				$tmpArr3[$v]['target3'] = $shopTarget['target3'];
				$tmpArr3[$v]['total'] += $cashTotal;
			}elseif($shopTarget['shop_code'] == 'EPPC' || $shopTarget['shop_code'] == 'EPIC'){
				$tmpArr['EP_GROUP']['target1'] += $shopTarget['target'];
				$tmpArr['EP_GROUP']['target2'] += $shopTarget['target2'];
				$tmpArr['EP_GROUP']['target3'] += $shopTarget['target3'];
				$tmpArr['EP_GROUP']['htarget1'] += $shopTarget['htarget'];
				$tmpArr['EP_GROUP']['htarget2'] += $shopTarget['htarget2'];
				$tmpArr['EP_GROUP']['htarget3'] += $shopTarget['htarget3'];
				while($startDate <= $dateEnd){
					$cash = $cashAccount->getActiveClosingByDate($v, $startDate,$startDate);
					$startDate = Model_DatetimeHelper::adjustDays('add', $startDate, 1);
					if($cash != null){
						$cashTotal += $cash[0]['apos_sys_sales_total'];
					}
					
				}
				$tmpArr['EP_GROUP']['total_sale'] += $cashTotal;
				$tmpArr3[$v]['target1'] = $shopTarget['target'];
				$tmpArr3[$v]['target2'] = $shopTarget['target2'];
				$tmpArr3[$v]['target3'] = $shopTarget['target3'];
				$tmpArr3[$v]['total'] += $cashTotal;
			}elseif($shopTarget['shop_code'] == 'PMPC' || $shopTarget['shop_code'] == 'PMIC'){
			
				$tmpArr['PM_GROUP']['target1'] += $shopTarget['target'];
				$tmpArr['PM_GROUP']['target2'] += $shopTarget['target2'];
				$tmpArr['PM_GROUP']['target3'] += $shopTarget['target3'];
				$tmpArr['PM_GROUP']['htarget1'] += $shopTarget['htarget'];
				$tmpArr['PM_GROUP']['htarget2'] += $shopTarget['htarget2'];
				$tmpArr['PM_GROUP']['htarget3'] += $shopTarget['htarget3'];
				while($startDate <= $dateEnd){
					$cash = $cashAccount->getActiveClosingByDate($v, $startDate,$startDate);
					$startDate = Model_DatetimeHelper::adjustDays('add', $startDate, 1);
					if($cash != null){
						$cashTotal += $cash[0]['apos_sys_sales_total'];
					}
					
				}
				$tmpArr['PM_GROUP']['total_sale'] += $cashTotal;
				$tmpArr3[$v]['target1'] = $shopTarget['target'];
				$tmpArr3[$v]['target2'] = $shopTarget['target2'];
				$tmpArr3[$v]['target3'] = $shopTarget['target3'];
				$tmpArr3[$v]['total'] += $cashTotal;
			}elseif($shopTarget['shop_code'] == 'WBPC' || $shopTarget['shop_code'] == 'WBIC'){
			
				$tmpArr['WB_GROUP']['target1'] += $shopTarget['target'];
				$tmpArr['WB_GROUP']['target2'] += $shopTarget['target2'];
				$tmpArr['WB_GROUP']['target3'] += $shopTarget['target3'];
				$tmpArr['WB_GROUP']['htarget1'] += $shopTarget['htarget'];
				$tmpArr['WB_GROUP']['htarget2'] += $shopTarget['htarget2'];
				$tmpArr['WB_GROUP']['htarget3'] += $shopTarget['htarget3'];
				while($startDate <= $dateEnd){
					$cash = $cashAccount->getActiveClosingByDate($v, $startDate,$startDate);
					$startDate = Model_DatetimeHelper::adjustDays('add', $startDate, 1);
					if($cash != null){
						$cashTotal += $cash[0]['apos_sys_sales_total'];
					}
					
				}
				$tmpArr['WB_GROUP']['total_sale'] += $cashTotal;
				$tmpArr3[$v]['target1'] = $shopTarget['target'];
				$tmpArr3[$v]['target2'] = $shopTarget['target2'];
				$tmpArr3[$v]['target3'] = $shopTarget['target3'];
				$tmpArr3[$v]['total'] += $cashTotal;
			}elseif($shopTarget['shop_code'] == 'WGPC' || $shopTarget['shop_code'] == 'WGIC'){
				
				$tmpArr['WG_GROUP']['target1'] += $shopTarget['target'];
				$tmpArr['WG_GROUP']['target2'] += $shopTarget['target2'];
				$tmpArr['WG_GROUP']['target3'] += $shopTarget['target3'];
				$tmpArr['WG_GROUP']['htarget1'] += $shopTarget['htarget'];
				$tmpArr['WG_GROUP']['htarget2'] += $shopTarget['htarget2'];
				$tmpArr['WG_GROUP']['htarget3'] += $shopTarget['htarget3'];
				while($startDate <= $dateEnd){
					$cash = $cashAccount->getActiveClosingByDate($v, $startDate,$startDate);
					$startDate = Model_DatetimeHelper::adjustDays('add', $startDate, 1);
					if($cash != null){
						$cashTotal += $cash[0]['apos_sys_sales_total'];
					}
					
				}
				$tmpArr['WG_GROUP']['total_sale'] += $cashTotal;
				$tmpArr3[$v]['target1'] = $shopTarget['target'];
				$tmpArr3[$v]['target2'] = $shopTarget['target2'];
				$tmpArr3[$v]['target3'] = $shopTarget['target3'];
				$tmpArr3[$v]['total'] += $cashTotal;
			}else{

				$tmpArr[$shopTarget['shop_code']]['target1'] = $shopTarget['target'];
				$tmpArr[$shopTarget['shop_code']]['target2'] = $shopTarget['target2'];
				$tmpArr[$shopTarget['shop_code']]['target3'] = $shopTarget['target3'];
				$tmpArr[$shopTarget['shop_code']]['htarget1'] = $shopTarget['htarget'];
				$tmpArr[$shopTarget['shop_code']]['htarget2'] = $shopTarget['htarget2'];
				$tmpArr[$shopTarget['shop_code']]['htarget3'] = $shopTarget['htarget3'];
				while($startDate <= $dateEnd){
					$cash = $cashAccount->getActiveClosingByDate($v, $startDate,$startDate);
					$startDate = Model_DatetimeHelper::adjustDays('add', $startDate, 1);
					if($cash != null){
						$cashTotal += $cash[0]['apos_sys_sales_total'];
					}
					
				}
				$tmpArr[$shopTarget['shop_code']]['total_sale'] = $cashTotal;
				$tmpArr3[$v]['target1'] = $shopTarget['target'];
				$tmpArr3[$v]['target2'] = $shopTarget['target2'];
				$tmpArr3[$v]['target3'] = $shopTarget['target3'];
				$tmpArr3[$v]['total'] += $cashTotal;
			}
			}
			}
			$targetList = $tmpArr;
			$shopList = $tmpArr3;
		}
		//d($targetList);
		
		$this->view->targetList = $targetList;
		
		$groupList = array(1 => 'ADPC',6 => 'CLPC', 17 => 'WLIC');
		
		if(isset($_POST['submit'])){
			$ShopBonus = array();
			foreach($_POST['shop'] as $k => $v){
				$tmpArr2 = array();
				$key = array_search($k,$groupList);

				$tmpArr2 = array();
				$tmpArr2['shop_id'] = $key;
				$tmpArr2['shop_code'] = $v;
				$tmpArr2['bonus1'] = $_POST['bonus1'][$k];
				$tmpArr2['bonus2'] = $_POST['bonus2'][$k];
				$tmpArr2['bonus3'] = $_POST['bonus3'][$k];
				$tmpArr2['final_bonus'] = $_POST['final_bonus'][$k];
				$ShopBonus[] = $tmpArr2;
				
			}
			
			foreach($ShopBonus as $key => $val){
				$bonus = $bonusRecord->getBonusRecordByShopIdDate($val['shop_id'], $dateBegin, $dateEnd);
				//d($bonus);
				if(!$bonus){
					$bonusRecord->addBonusRecord($val['shop_id'], $val['shop_code'] ,$val['bonus1'], $val['bonus2'], $val['bonus3'],$val['final_bonus'], $dateBegin, $dateEnd, 0);
				}else{
					
					$bonusRecord->updateFinalBonusRecord($bonus['id'], $val['final_bonus']);
				}
				
			}
			
			//d($ShopBonus);
			$url = "/staff/team-bonus-wizard-summary/date_begin/".$dateBegin."/date_end/".$dateEnd."/next/yes";
			$this->_redirect($url);
		}
			
	}
	
	public function teamBonusWizardNewCalBonusAction(){
		error_reporting(E_ALL ^ E_NOTICE);
		$bonusRecord = new Model_Payroll_Shopgroupbonusrecord();
		$shopArr = unserialize(ARR_SHOP_ACTIVE);
		$bonuscycle = unserialize(BONUS_CYCLE_2015);
		$target = new Model_DbTable_Target_Weeklytarget();
		$cashAccount = new Model_DbTable_Cashaccount_Remote_Closing();
		$tBonus = unserialize(T_BONUS_TARGET);
		$targetList = array();
		$shopList = array();
		
		
		$nextCheck = $this->_getParam("next");
		
		if($nextCheck == 'yes'){
			$check = true;
			$this->view->nextCheck = $check;
		}
		
		
		$dateBegin = $this->_getParam("date_begin");
		$dateEnd = $this->_getParam("date_end");
		$this->view->dateStart = $dateBegin;
		$this->view->dateEnd = $dateEnd;
		$cycleKey = 0;
		
		foreach($bonuscycle as $kc => $vc){
		
			if($dateBegin >= $vc[0] && $dateEnd <= $vc[1] ){
				$cycleKey = $kc + 1;
			}
		}
		$this->view->cycle = $cycleKey;
		
		$tmpArr = array();
		
		foreach($shopArr as $k => $v){
			$startDate = $dateBegin;
			$cashTotal = 0;
			$count = 0;
				
			$shopTarget = $target->getWeeklyTargetByShopByDate($v, $dateBegin);
			if(!empty($shopTarget)){
			  if($shopTarget['shop_code'] != 'CLPC' && $shopTarget['shop_code'] != 'ADPC' && $shopTarget['shop_code'] != 'WLIC'){
				if($shopTarget['shop_code'] == 'BSIC' || $shopTarget['shop_code'] == 'BSPC' || $shopTarget['shop_code'] == 'BSXP'){
		
					$tmpArr['BAYSIDE GROUP']['target1'] += $shopTarget['target'];
					$tmpArr['BAYSIDE GROUP']['target2'] += $shopTarget['target2'];
					$tmpArr['BAYSIDE GROUP']['target3'] += $shopTarget['target3'];
					$tmpArr['BAYSIDE GROUP']['htarget1'] = $tBonus['T1'] * 2;
					$tmpArr['BAYSIDE GROUP']['htarget2'] = $tBonus['T2'] * 2;
					$tmpArr['BAYSIDE GROUP']['htarget3'] = $tBonus['T3'] * 2;
		
					while($startDate <= $dateEnd){
						$cash = $cashAccount->getActiveClosingByDate($v, $startDate,$startDate);
						$startDate = Model_DatetimeHelper::adjustDays('add', $startDate, 1);
						if($cash != null){
							$cashTotal += $cash[0]['apos_sys_sales_total'];
						}
					}
					$tmpArr['BAYSIDE GROUP']['total_sale'] += $cashTotal;
		
					$tmpArr3[$v]['target1'] = $shopTarget['target'];
					$tmpArr3[$v]['target2'] = $shopTarget['target2'];
					$tmpArr3[$v]['target3'] = $shopTarget['target3'];
					$tmpArr3[$v]['total'] += $cashTotal;
				}elseif($shopTarget['shop_code'] == 'CBPC' || $shopTarget['shop_code'] == 'CBIC'){
					$tmpArr['CB GROUP']['target1'] += $shopTarget['target'];
					$tmpArr['CB GROUP']['target2'] += $shopTarget['target2'];
					$tmpArr['CB GROUP']['target3'] += $shopTarget['target3'];
					$tmpArr['CB GROUP']['htarget1'] = $tBonus['T1'] * 1.5;
					$tmpArr['CB GROUP']['htarget2'] = $tBonus['T2'] * 1.5;
					$tmpArr['CB GROUP']['htarget3'] = $tBonus['T3'] * 1.5;
					while($startDate <= $dateEnd){
						$cash = $cashAccount->getActiveClosingByDate($v, $startDate,$startDate);
						$startDate = Model_DatetimeHelper::adjustDays('add', $startDate, 1);
						if($cash != null){
							$cashTotal += $cash[0]['apos_sys_sales_total'];
						}
							
					}
					$tmpArr['CB GROUP']['total_sale'] += $cashTotal;
					$tmpArr3[$v]['target1'] = $shopTarget['target'];
					$tmpArr3[$v]['target2'] = $shopTarget['target2'];
					$tmpArr3[$v]['target3'] = $shopTarget['target3'];
					$tmpArr3[$v]['total'] += $cashTotal;
				}elseif($shopTarget['shop_code'] == 'PMPC' || $shopTarget['shop_code'] == 'PMIC'){
						
					$tmpArr['PM GROUP']['target1'] += $shopTarget['target'];
					$tmpArr['PM GROUP']['target2'] += $shopTarget['target2'];
					$tmpArr['PM GROUP']['target3'] += $shopTarget['target3'];
					$tmpArr['PM GROUP']['htarget1'] = $tBonus['T1'] * 1.5;
					$tmpArr['PM GROUP']['htarget2'] = $tBonus['T2'] * 1.5;
					$tmpArr['PM GROUP']['htarget3'] = $tBonus['T3'] * 1.5;
					while($startDate <= $dateEnd){
						$cash = $cashAccount->getActiveClosingByDate($v, $startDate,$startDate);
						$startDate = Model_DatetimeHelper::adjustDays('add', $startDate, 1);
						if($cash != null){
							$cashTotal += $cash[0]['apos_sys_sales_total'];
						}
							
					}
					$tmpArr['PM GROUP']['total_sale'] += $cashTotal;
					$tmpArr3[$v]['target1'] = $shopTarget['target'];
					$tmpArr3[$v]['target2'] = $shopTarget['target2'];
					$tmpArr3[$v]['target3'] = $shopTarget['target3'];
					$tmpArr3[$v]['total'] += $cashTotal;
				}elseif($shopTarget['shop_code'] == 'WBPC' || $shopTarget['shop_code'] == 'WBIC'){
						
					$tmpArr['WB GROUP']['target1'] += $shopTarget['target'];
					$tmpArr['WB GROUP']['target2'] += $shopTarget['target2'];
					$tmpArr['WB GROUP']['target3'] += $shopTarget['target3'];
					$tmpArr['WB GROUP']['htarget1'] = $tBonus['T1'] * 1.5;
					$tmpArr['WB GROUP']['htarget2'] = $tBonus['T2'] * 1.5;
					$tmpArr['WB GROUP']['htarget3'] = $tBonus['T3'] * 1.5;
					while($startDate <= $dateEnd){
						$cash = $cashAccount->getActiveClosingByDate($v, $startDate,$startDate);
						$startDate = Model_DatetimeHelper::adjustDays('add', $startDate, 1);
						if($cash != null){
							$cashTotal += $cash[0]['apos_sys_sales_total'];
						}
							
					}
					$tmpArr['WB GROUP']['total_sale'] += $cashTotal;
					$tmpArr3[$v]['target1'] = $shopTarget['target'];
					$tmpArr3[$v]['target2'] = $shopTarget['target2'];
					$tmpArr3[$v]['target3'] = $shopTarget['target3'];
					$tmpArr3[$v]['total'] += $cashTotal;
				}elseif($shopTarget['shop_code'] == 'WGPC' || $shopTarget['shop_code'] == 'WGIC'){
		
					$tmpArr['WG GROUP']['target1'] += $shopTarget['target'];
					$tmpArr['WG GROUP']['target2'] += $shopTarget['target2'];
					$tmpArr['WG GROUP']['target3'] += $shopTarget['target3'];
					$tmpArr['WG GROUP']['htarget1'] = $tBonus['T1'] * 1.5;
					$tmpArr['WG GROUP']['htarget2'] = $tBonus['T2'] * 1.5;
					$tmpArr['WG GROUP']['htarget3'] = $tBonus['T3'] * 1.5;
					while($startDate <= $dateEnd){
						$cash = $cashAccount->getActiveClosingByDate($v, $startDate,$startDate);
						$startDate = Model_DatetimeHelper::adjustDays('add', $startDate, 1);
						if($cash != null){
							$cashTotal += $cash[0]['apos_sys_sales_total'];
						}
							
					}
					$tmpArr['WG GROUP']['total_sale'] += $cashTotal;
					$tmpArr3[$v]['target1'] = $shopTarget['target'];
					$tmpArr3[$v]['target2'] = $shopTarget['target2'];
					$tmpArr3[$v]['target3'] = $shopTarget['target3'];
					$tmpArr3[$v]['total'] += $cashTotal;
				}else{
					if($shopTarget['shop_code'] == 'EPIC'){
					
						$tmpArr[$shopTarget['shop_code']]['target1'] = $shopTarget['target'];
						$tmpArr[$shopTarget['shop_code']]['target2'] = $shopTarget['target2'];
						$tmpArr[$shopTarget['shop_code']]['target3'] = $shopTarget['target3'];
						$tmpArr[$shopTarget['shop_code']]['htarget1'] = 800;
						$tmpArr[$shopTarget['shop_code']]['htarget2'] = 100;
						$tmpArr[$shopTarget['shop_code']]['htarget3'] = 100;
							while($startDate <= $dateEnd){
								$cash = $cashAccount->getActiveClosingByDate($v, $startDate,$startDate);
								$startDate = Model_DatetimeHelper::adjustDays('add', $startDate, 1);
								if($cash != null){
									$cashTotal += $cash[0]['apos_sys_sales_total'];
								}		
							}
						$tmpArr[$shopTarget['shop_code']]['total_sale'] = $cashTotal;
						$tmpArr3[$v]['target1'] = $shopTarget['target'];
						$tmpArr3[$v]['target2'] = $shopTarget['target2'];
						$tmpArr3[$v]['target3'] = $shopTarget['target3'];
						$tmpArr3[$v]['total'] += $cashTotal;
					}else if ($shopTarget['shop_code'] == 'BBPC'){
						$tmpArr[$shopTarget['shop_code']]['target1'] = $shopTarget['target'];
						$tmpArr[$shopTarget['shop_code']]['target2'] = $shopTarget['target2'];
						$tmpArr[$shopTarget['shop_code']]['target3'] = $shopTarget['target3'];
						$tmpArr[$shopTarget['shop_code']]['htarget1'] = 400;
						$tmpArr[$shopTarget['shop_code']]['htarget2'] = 100;
						$tmpArr[$shopTarget['shop_code']]['htarget3'] = 100;
						while($startDate <= $dateEnd){
							$cash = $cashAccount->getActiveClosingByDate($v, $startDate,$startDate);
							$startDate = Model_DatetimeHelper::adjustDays('add', $startDate, 1);
							if($cash != null){
								$cashTotal += $cash[0]['apos_sys_sales_total'];
							}
								
						}
						$tmpArr[$shopTarget['shop_code']]['total_sale'] = $cashTotal;
						$tmpArr3[$v]['target1'] = $shopTarget['target'];
						$tmpArr3[$v]['target2'] = $shopTarget['target2'];
						$tmpArr3[$v]['target3'] = $shopTarget['target3'];
						$tmpArr3[$v]['total'] += $cashTotal;
					}else{
						$tmpArr[$shopTarget['shop_code']]['target1'] = $shopTarget['target'];
						$tmpArr[$shopTarget['shop_code']]['target2'] = $shopTarget['target2'];
						$tmpArr[$shopTarget['shop_code']]['target3'] = $shopTarget['target3'];
						$tmpArr[$shopTarget['shop_code']]['htarget1'] = $tBonus['T1'];
						$tmpArr[$shopTarget['shop_code']]['htarget2'] = $tBonus['T2'];
						$tmpArr[$shopTarget['shop_code']]['htarget3'] = $tBonus['T3'];
						while($startDate <= $dateEnd){
							$cash = $cashAccount->getActiveClosingByDate($v, $startDate,$startDate);
							$startDate = Model_DatetimeHelper::adjustDays('add', $startDate, 1);
							if($cash != null){
								$cashTotal += $cash[0]['apos_sys_sales_total'];
							}
								
						}
						$tmpArr[$shopTarget['shop_code']]['total_sale'] = $cashTotal;
						$tmpArr3[$v]['target1'] = $shopTarget['target'];
						$tmpArr3[$v]['target2'] = $shopTarget['target2'];
						$tmpArr3[$v]['target3'] = $shopTarget['target3'];
						$tmpArr3[$v]['total'] += $cashTotal;
					}
				}
			}
		   }
			$targetList = $tmpArr;
			$shopList = $tmpArr3;
		}
		$this->view->targetList = $targetList;
		$this->view->shopList = $shopList;
		
		$groupList = unserialize(ARR_SHOP_GROUP);
		if(isset($_POST['next'])){
			$ShopBonus = array();
			foreach($_POST['shop'] as $k => $v){
				
				
				$key = array_search($k,$groupList);
				if($key){
					$tmpArr2 = array();
					$tmpArr2['shop_id'] = $key;
					$tmpArr2['shop_code'] = $v;
					$tmpArr2['bonus1'] = $_POST['bonus1'][$k];
					$tmpArr2['bonus2'] = $_POST['bonus2'][$k];
					$tmpArr2['bonus3'] = $_POST['bonus3'][$k];
					$tmpArr2['final_bonus'] = $_POST['final_bonus'][$k];
					$ShopBonus[] = $tmpArr2;
				}
			}
			foreach($ShopBonus as $key => $val){
				$bonus = $bonusRecord->getBonusRecordByShopIdDate($val['shop_id'], $dateBegin, $dateEnd);
				
				if(!$bonus){
					$bonusRecord->addBonusRecord($val['shop_id'], $val['shop_code'] ,$val['bonus1'], $val['bonus2'], $val['bonus3'],$val['final_bonus'], $dateBegin, $dateEnd, 0);
				}else{
					$bonusRecord->updateFinalBonusRecord($bonus['id'], $val['final_bonus']);
				}
				
			}
			$url = "/staff/team-bonus-wizard-new-summary/date_begin/".$dateBegin."/date_end/".$dateEnd."/next/yes";
			$this->_redirect($url);
		}
		
		
		
	}
	
	
	public function teamBonusWizardNewSummaryAction(){
		$bos = new Model_Payroll_Shopgroupbonus();
		$bonusRecord = new Model_Payroll_Shopgroupbonusrecord();
		$carryBonus = new Model_Payroll_Shopgroupcarrybonus();
		$shopGroup = unserialize(ARR_SHOP_GROUP);
		$cycle = unserialize(BONUS_CYCLE_2015);
		
		
		$nextCheck = $this->_getParam("next");
		$periodBegin = $this->_getParam("date_begin");
		$periodEnd = $this->_getParam("date_end");
		if($nextCheck == 'yes'){
			$check = true;
			$this->view->nextCheck = $check;
		}
		$this->view->dateStart = $periodBegin;
		$this->view->dateEnd = $periodEnd;
		
		foreach($cycle as $k2 => $v2){ //get current cycle key
			if($periodBegin >= $v2[0] && $periodEnd <= $v2[1] ){
				$cycleKey = $k2;
			}
				
		}
		$this->view->cycle = $cycleKey + 1;
		
		$nextCycleBegin = $cycle[$cycleKey + 1][0];  //get next cycle
		$nextCycleEnd = $cycle[$cycleKey + 1][1];
		
		$bonusList = array();
		
		foreach($shopGroup as $key => $val){
			
			if($key != 1 && $key != 6 && $key != 7 && $key != 17){
			$otherLost = 0;
			$tmpArr2 = array();
			$tmp1 = $bos->getAllStockLostByShopByType($val, $periodBegin, $periodEnd,10);
			if(!$tmp1){
				$otherLost = 0;
			}else{
				foreach($tmp1 as $k3 => $v3){
					$otherLost += $v3['amt_total_bonus'];
				}
			}
				
			$tmpArr2['id_shop'] = $key;
			$tmpArr2['shop_code']  = $val;
			$tmpArr2['total_other_lost'] = $otherLost;
			$bonus = $bonusRecord->getBonusRecordByShopIdDate($key, $periodBegin, $periodEnd);
			$tmpArr2['final_bonus'] = $bonus['final_bonus'];

			if($bonus['final_bonus'] == 0){
				$tmpArr2['net_bonus'] = 0;
			}else{
				$netBonus = $bonus['final_bonus'] + $otherLost;
				
				if($netBonus <= 0){
					$tmpArr2['net_bonus'] = 0;
				}else{
					$tmpArr2['net_bonus'] = $netBonus;
				}
				 
			}
				
		
			$bonusList[] = $tmpArr2;
			}
		}
		$this->view->bonusList = $bonusList;

		if(isset($_POST['next'])){

			foreach($_POST['shop_code'] as $k => $v){
				//update net bonus
				$bonusRecord->updateNetBonus(($k), $periodBegin, $periodEnd, $_POST['net_bonus'][$k]);
			}
				
			$url = "/staff/team-bonus-wizard-new-distribution/date_begin/".$periodBegin."/date_end/".$periodEnd."/next/yes";
			$this->_redirect($url);
		}
	}
	
	
	/**
	 * Add stock lost for calculate teambonus 
	 * 2 types current/carryforward stock lost
	 * @version 2014-08-19
	 * @author Leo
	 */
	public function teamBonusWizardAddStocklossAction(){
		
		$shopList = unserialize(ARR_SHOP_GROUP);
		$cycle = unserialize(BONUS_CYCLE_2015);

		$periodBegin = "";
		$periodEnd = "";

		
		$periodBegin = $this->_getParam("date_begin");
		$periodEnd = $this->_getParam("date_end");
		$this->view->dateStart = $periodBegin;
		$this->view->dateEnd = $periodEnd;
		
		foreach($cycle as $k2 => $v2){
			if($periodBegin >= $v2[0] && $periodEnd <= $v2[1] ){
				$cycleKey = $k2;
			}
		}
		$this->view->cycle = $cycleKey+1;

		$nextCheck = $this->_getParam("next");
		
		if($nextCheck == 'yes'){
			$check = true;
			$this->view->nextCheck = $check;
		}
		
		$this->view->periodBegin = $periodBegin;
		$this->view->periodEnd = $periodEnd;
		$bos = new Model_Payroll_Shopgroupbonus();
		
		$ShopLost = array();
		foreach($shopList as $k => $v){
			$tmpArr = array();
			$stockLost = $bos->getStockLostByShopByType($v, $periodBegin, $periodEnd,5);
			$tmpArr['shop_code']  = $v;
			$tmpArr['before_stocklost'] = $stockLost['amt_total_bonus'];
			$ShopLost[] = $tmpArr;
		}
		
		$this->view->stocklost = $ShopLost;
		
		if(isset($_POST['button'])){
			$newStockLost = array();
			foreach($_POST['shop_code'] as $key => $val){
				$bosCheck = $bos->getStockLostByShopByType($val, $periodBegin, $periodEnd, 4);
				if(!$bosCheck){
					$bos->newShopbonus(($key+1), 4, $periodBegin." current lost", $_POST['current_stocklost'][$key], $_POST['current_stocklost'][$key], 0, 0, $periodBegin, $periodEnd, '0000-00-00', 0, '0000-00-00', 'none',$val);
				}
				$tmpArr2 = array();
				$bfstockLost = $bos->getStockLostByShopByType($val, $periodBegin, $periodEnd,5);
				$currentStockLost = $bos->getStockLostByShopByType($val, $periodBegin, $periodEnd,4);

				$tmpArr2['shop_code']  = $val;
				$tmpArr2['before_stocklost'] = $bfstockLost['amt_total_bonus'];
				$tmpArr2['current_stocklost'] = $currentStockLost['amt_total_bonus'];
				$newStockLost[] = $tmpArr2;
			}
			
			$this->view->newStockLost = $newStockLost;

			echo "Add stock lost success";
		}
		
		if(isset($_POST['next'])){
			foreach($_POST['shop_code'] as $key => $val){
				$bosCheck = $bos->getStockLostByShopByType($val, $periodBegin, $periodEnd, 6);
				if(!$bosCheck){
					$bos->newShopbonus(($key+1), 6, $periodBegin." adjusted lost", $_POST['adj_total'][$key], $_POST['adj_total'][$key], 0, 0, $periodBegin, $periodEnd, '0000-00-00', 0, '0000-00-00', 'none',$val);
				}else{
					$bos->updateAdjStockLost($bosCheck['id_bonus'], $_POST['adj_total'][$key], $_POST['adj_total'][$key]);
				}
			}
			$url = "/staff/team-bonus-wizard-summary/date_begin/".$periodBegin."/date_end/".$periodEnd."/next/yes";
			$this->_redirect($url);
		}
	
	}
	
	
	/**
	 * This function is for calculate staff teambonus
	 * Only select staff will get bonus
	 * @version 2014-08-20
	 * @author Leo
	 */
	
	public function teamBonusWizardDistributionAction(){
		error_reporting(E_ALL ^ E_NOTICE);
		$bonusRecord = new Model_Payroll_Shopgroupbonusrecord();
		$attRecord = new Model_DbTable_Roster_Attnrecord();
		$forwardBonus = new Model_Payroll_Shopgroupcarrybonus();
		$stfBonus = new Model_Payroll_Staffbonus();
		$groupShops = unserialize(ARR_GROUP_SHOPS);
		$groupList = unserialize(ARR_SHOP_GROUP);
		$cycles = unserialize(BONUS_CYCLE_2015);
		$stInfo = new Model_DbTable_Roster_Staffinfo();
		$ts = new Model_DbTable_Roster_Timesheet();
		$nextCheck = $this->_getParam("next");
		$dateBegin = $this->_getParam("date_begin");
		$dateEnd = $this->_getParam("date_end");
		if($nextCheck == 'yes'){
			$check = true;
			$this->view->nextCheck = $check;
		}

		foreach($cycles as $k2 => $v2){
			if($dateBegin >= $v2[0] && $dateEnd <= $v2[1] ){
				$cycleKey = $k2;
			}
		}
		$idCycle = $cycleKey + 1;
		
		$nextCycleBegin = $cycles[$idCycle][0];
		$nextCycleEnd = $cycles[$idCycle][1];
		
		//$bonus = $this->_getParam("bonus");
		//$idGroup = $this->_getParam("id_group");
		//$idCycle = $this->_getParam('cycle');

		$this->view->dateBegin = $dateBegin;
		$this->view->dateEnd = $dateEnd;
		$this->view->cycle = $idCycle;
		$bonusRecordList = array();
		foreach($groupShops as $key2 => $val2){
			if($key2 == 1 || $key2 == 6 || $key2 == 17){
			$tmpArr = array();
			$tmpArr = $bonusRecord->getBonusRecordByShopIdDate($key2, $dateBegin, $dateEnd);
			$bonusRecordList[$key2] = $tmpArr;
			}
		}
		

		//d($bonus,$dateBegin,$dateEnd,$arrSHops);
		
		
		
		// calculate Should Paid Hours
		
		
			
		$arrayList = array();
		$arrMgr = array();
		$arrSc = array();
		$arrFt = array();
		$arrStName = array();
		$arrWkHr = array();
		foreach($bonusRecordList as $k3 => $v3){
			if($v3['net_bonus'] > 0){
			
			$arrShops = $groupShops[$k3];
			$arrayList[$k3]['bonus'][] = $v3['net_bonus'];
			$arrStaff = array();
			
			
			foreach($arrShops as $shop){
				
				$tsList = $ts->listConfirmedShiftByDateByShop($shop, $dateBegin, $dateEnd);
				foreach($tsList as $line){
		
					$arrStaff[$k3][] = $line['id_staff'];
				}
				
			}
			$arrStaff = array_unique($arrStaff[$k3]);

		//d($arrStaff);

			foreach($arrStaff as $idStaff){
				
				$stLine = $stInfo->getStaffinfo($idStaff);
				
				$arrStName[$idStaff] = $stLine['first_name'].' '.$stLine['last_name'];
				
				if($stLine['position_status'] == 5 || $stLine['position_status'] == 6 ){
		
					$arrayList[$k3]['manager'][] = $idStaff;
				}
				elseif($stLine['position_status'] == 1 || $stLine['position_status'] == 2 || $stLine['position_status'] == 3   ){
					$arrayList[$k3]['ft'][] = $idStaff;
					$arrayList[$k3]['sc'][] = 0;
					$arrayList[$k3]['manager'][] = 0;
				}
				elseif($stLine['position_status'] == 4){
					$arrayList[$k3]['sc'][] = $idStaff;
				}
				elseif($stLine['position_status'] == 7 || $stLine['position_status'] == 99 || $stLine['position_status'] == 8){
		
				}
				else{
					$arrayList[$k3]['ft'][] = $idStaff;
					
				}
		
			}

		//find every singl one total working hours in the group

			$arrDate = Model_DatetimeHelper::createDateArray($dateBegin, $dateEnd);

			foreach($arrStaff as $idStaff){
				
				foreach($arrShops as $shop){
					foreach($arrDate as $dateToCheck){
					//find Shift in that
						$shiftLine = $ts->listAllShiftByStaffIdByDateByShop($idStaff, $shop, $dateToCheck, $dateToCheck);
						$attLine = $attRecord->getFirstOnLastOffDuty($idStaff, $dateToCheck,Model_EncryptHelper::sslPassword($shop));
						
						
						foreach($shiftLine as $key => $v){
							
							$firstBreak = 0;
							$breakTime = 1800;
		
							if($v["break_time"]===(int)0 and $v["break_time"]!== null ){
								$breakTime  = 0;
							}
							if((($v["confirm_shift_end"]-$v["confirm_shift_begin"])<18000) && ($v["break_time"] == 0 ||$v["break_time"]== null )){
								
								$breakTime = 0;
							}
							
							if(($v["confirm_shift_end"]-$v["confirm_shift_begin"]) >= 32400){
								
								$firstBreak = 1800;
		
							}
							
							
							$manShiftBegin = $v["confirm_shift_begin"];
							$manShiftEnd = $v["confirm_shift_end"];
							$actBegin = $attLine[0];
							$actEnd = $attLine[1];
							
							$shiftBegin = 0;
							$shiftEnd = 0;
						
							$wkHr = 0;
							
							if( $manShiftBegin != null && $manShiftEnd != null && $actBegin != null && $actEnd != null ){
		
								$shiftBegin = ($manShiftBegin > $actBegin)?$manShiftBegin:$actBegin;
								$shiftEnd = ($manShiftEnd < $actEnd)?$manShiftEnd: $actEnd;
		
							}
							
							//d($shiftBegin,$shiftEnd);
							
							$wkHr = $shiftEnd - $shiftBegin - $breakTime - $firstBreak;
							
							if($wkHr >0 ){
		
								if(isset($arrWkHr[$idStaff])){
									$arrayList[$k3]['wk'][$idStaff] += round($wkHr/3600,2);
								}
								else{
									$arrayList[$k3]['wk'][$idStaff] += round($wkHr/3600,2);
								}
		
							}

						}		
					}
		
				}
			  }
			}
		}
			$this->view->arrList = $arrayList;
			$this->view->arrStName = $arrStName;
			
			//d($arrMgr,$arrSc,$arrFt,$arrWkHr,$arrStName);
		
			if($_POST){
			//d($_POST);
				$carryBonus = array();
				$staffBonus = array();
				foreach($_POST['group_code'] as $k => $v){
				$bonus = $bonusRecord->getBonusRecordByShopIdDate($k, $dateBegin, $dateEnd);
				
					if(isset($_POST['is_mMgr'][$k])&&isset($_POST['is_mgr'][$k])){
						$amtmMgr = round($bonus['net_bonus']*0.2,2,PHP_ROUND_HALF_DOWN);
						$amtMgr = round(($bonus['net_bonus'])*0.5,2,PHP_ROUND_HALF_DOWN);
						$amtSc = round(($bonus['net_bonus'])*0.25,2,PHP_ROUND_HALF_DOWN);
						$amtFt = round(($bonus['net_bonus'])*0.05,2,PHP_ROUND_HALF_DOWN);
						//d($amtmMgr,$amtMgr,$amtSc,$amtFt,$bonus);
						echo '<br/>','Group:'.$groupList[$v],'<br/>';
						echo "Multi Manager is ".$arrStName[key($_POST['is_mMgr'][$k])]." will take 20% : ". $bonus['net_bonus'] ." = $ ".$amtmMgr."<br />";
						$staffBonus[key($_POST['is_mMgr'][$k])] += $amtmMgr;
						
						echo "Manager is ".$arrStName[key($_POST['is_mgr'][$k])]." will take 50% : ". ($bonus['net_bonus']) ." x  50% = $ ".$amtMgr."<br />";
						$staffBonus[key($_POST['is_mgr'][$k])] += $amtMgr;
						
						if(isset($_POST['is_sc'][$k])){
						
							$scCount = count($_POST['is_sc'][$k]);
							$precenter = 1/$scCount;
							foreach($_POST['is_sc'][$k] as $k3 => $v3){
								echo "SC is ".$arrStName[$k3]." will take ".round($precenter*100,2,PHP_ROUND_HALF_DOWN)."% of 25% : ". ($bonus['net_bonus']) ." x  25% x ".round($precenter*100,2,PHP_ROUND_HALF_DOWN)."%   = $ ".round($amtSc*$precenter,2,PHP_ROUND_HALF_DOWN)."<br />";
								$staffBonus[$k3] += round($amtSc*$precenter,2,PHP_ROUND_HALF_DOWN);
							}
								
						}else{
							echo "There is No SC will Forward 25% :". ($bonus['net_bonus']) ." x  25% = $ ".$amtSc."<br />";
							$carryBonus[$v]['carry_bonus'] += $amtSc;
						}
						
							
						if(isset($_POST['is_ft'][$k])){
							$TotalFullWkHr = array_sum($_POST['is_ft'][$k]);
								
							foreach($_POST['is_ft'][$k] as $k2 => $v2){
								echo "Full Time/Part Time Staff: ".$arrStName[$k2]." Working Hr : ".$v2." hr, is ".round($v2/$TotalFullWkHr*100,2,PHP_ROUND_HALF_DOWN)."% Total ".$TotalFullWkHr." hr , Amt is ".($bonus['net_bonus'])." x 5% x ";
								echo round($v2/$TotalFullWkHr*100,2,PHP_ROUND_HALF_DOWN)."% = $ ".round($amtFt * $v2/$TotalFullWkHr,2,PHP_ROUND_HALF_DOWN)."<br />";
								$staffBonus[$k2] += round($amtFt * $v2/$TotalFullWkHr,2,PHP_ROUND_HALF_DOWN);
							}
						
						}else{
							echo "No Full Time Here Forward That 25% ".$amtFt."<br />";
							$carryBonus[$v]['carry_bonus'] += $amtFt;
						}
					}elseif(isset($_POST['is_mMgr'][$k])&&!$_POST['is_mgr'][$k]){
						$amtMgr = round($bonus['net_bonus']*0.5,2);
						$amtSc = round($bonus['net_bonus']*0.25,2);
						$amtFt = round($bonus['net_bonus']*0.25,2);
						//d($amtmMgr,$amtMgr,$amtSc,$amtFt,$bonus);
						echo '<br/>','Group:'.$groupList[$v],'<br/>';

						echo "Multi Manager is ".$arrStName[key($_POST['is_mMgr'][$k])]." will take 50% : ". $bonus['net_bonus'] ." x  50% = $ ".$amtMgr."<br />";
						$staffBonus[key($_POST['is_mMgr'][$k])] += $amtMgr;
						
						if(isset($_POST['is_sc'][$k])){
						
							$scCount = count($_POST['is_sc'][$k]);
							$precenter = 1/$scCount;
							foreach($_POST['is_sc'][$k] as $k3 => $v3){
								echo "SC is ".$arrStName[$k3]." will take ".round($precenter*100,2,PHP_ROUND_HALF_DOWN)."% of 25% : ". $bonus['net_bonus'] ." x  25% x ".round($precenter*100,2,PHP_ROUND_HALF_DOWN)."%   = $ ".round($amtSc*$precenter,2,PHP_ROUND_HALF_DOWN)."<br />";
								$staffBonus[$k3] += round($amtSc*$precenter,2,PHP_ROUND_HALF_DOWN);
							}
								
						}else{
							echo "There is No SC will Forward 25% :". $bonus['net_bonus'] ." x  25% = $ ".$amtSc."<br />";
							$carryBonus[$v]['carry_bonus'] += $amtSc;
						}
						
							
						if(isset($_POST['is_ft'][$k])){
							$TotalFullWkHr = array_sum($_POST['is_ft'][$k]);
								
							foreach($_POST['is_ft'][$k] as $k2 => $v2){
								echo "Full Time/Part Time Staff: ".$arrStName[$k2]." Working Hr : ".$v2." hr, is ".round($v2/$TotalFullWkHr*100,2,PHP_ROUND_HALF_DOWN)."% Total ".$TotalFullWkHr." hr , Amt is ".$bonus['net_bonus']." X 25% x ";
								echo round($v2/$TotalFullWkHr*100,2,PHP_ROUND_HALF_DOWN)."% = $ ".round($amtFt * $v2/$TotalFullWkHr,2,PHP_ROUND_HALF_DOWN)."<br />";
								$staffBonus[$k2] += round($amtFt * $v2/$TotalFullWkHr,2,PHP_ROUND_HALF_DOWN);
							}
						
						}else{
							echo "No Full Time Here Forward That 25% ".$amtFt."<br />";
							$carryBonus[$v]['carry_bonus'] += $amtFt;
						}
					}
					else{
				
						$amtMgr = round($bonus['net_bonus']*0.5,2);
						$amtSc = round($bonus['net_bonus']*0.25,2);
						$amtFt = round($bonus['net_bonus']*0.25,2);
						echo '<br/>','Group:'.$groupList[$v],'<br/>';
						if(isset($_POST['is_mgr'][$k])){
				
							echo "Manager is ".$arrStName[key($_POST['is_mgr'][$k])]." will take 50% : ". $bonus['net_bonus'] ." x  50% = $ ".$amtMgr."<br />";
							$staffBonus[key($_POST['is_mgr'][$k])] += $amtMgr;
						}else{
							echo "There is No Manager will Forward 50% :". $bonus['net_bonus'] ." x  50% = $ ".$amtMgr."<br />";
							$carryBonus[$v]['carry_bonus'] += $amtMgr;
						
						}
						if(isset($_POST['is_sc'][$k])){
				
							$scCount = count($_POST['is_sc'][$k]);
							$precenter = 1/$scCount;
							foreach($_POST['is_sc'][$k] as $k3 => $v3){
								echo "SC is ".$arrStName[$k3]." will take ".round($precenter*100,2,PHP_ROUND_HALF_DOWN)."% of 25% : ". $bonus['net_bonus'] ." x  25% x ".round($precenter*100,2,PHP_ROUND_HALF_DOWN)."%   = $ ".round($amtSc*$precenter,2,PHP_ROUND_HALF_DOWN)."<br />";	
								$staffBonus[$k3] += round($amtSc*$precenter,2,PHP_ROUND_HALF_DOWN);
							}
					
						}else{
							echo "There is No SC will Forward 25% :". $bonus['net_bonus'] ." x  25% = $ ".$amtSc."<br />";
							$carryBonus[$v]['carry_bonus'] += $amtSc;
						}
				    
					
						if(isset($_POST['is_ft'][$k])){
							$TotalFullWkHr = array_sum($_POST['is_ft'][$k]);
					
							foreach($_POST['is_ft'][$k] as $k2 => $v2){
								echo "Full Time/Part Time Staff: ".$arrStName[$k2]." Working Hr : ".$v2." hr, is ".round($v2/$TotalFullWkHr*100,2,PHP_ROUND_HALF_DOWN)."% Total ".$TotalFullWkHr." hr , Amt is ".$bonus['net_bonus']." X 25% x ";
								echo round($v2/$TotalFullWkHr*100,2,PHP_ROUND_HALF_DOWN)."% = $ ".round($amtFt * $v2/$TotalFullWkHr,2,PHP_ROUND_HALF_DOWN)."<br />";
								$staffBonus[$k2] += round($amtFt * $v2/$TotalFullWkHr,2,PHP_ROUND_HALF_DOWN);
							}
						
						}else{
							echo "No Full Time Here Forward That 25% ".$amtFt."<br />";
							$carryBonus[$v]['carry_bonus'] += $amtFt;
						}
					}
				}
			
				foreach($carryBonus as $k4 => $v4){
					$checkForwardBonuse = $forwardBonus->getCarryBonusByShopIdDate($k4, $nextCycleBegin, $nextCycleEnd);
					if(!$checkForwardBonuse){
						$forwardBonus->addCarryBonus($k4, $groupList[$k4], 1 , $v4['carry_bonus'], $nextCycleBegin, $nextCycleEnd);
					}
				}
				
				foreach($staffBonus as $k5 => $v5){
					$staffDetail = $stInfo->getStaffinfo($k5);
					//pay by bank
					if($staffDetail['id_package'] == 1 || $staffDetail['id_package'] == 3 || $staffDetail['id_package'] == 4 || $staffDetail['id_package'] == 6 || $staffDetail['id_package'] == 7 || $staffDetail['id_package'] == 8){
						$amtBank = round($v5/1.095,2);
						$amtSuper = round($v5-$amtBank,2);
						$stfBonus->newStaffbonus($k5, 3, "Cycle".$idCycle." Bonus", $v5, 0, $amtBank, $amtSuper, $dateBegin, $dateEnd, '0000-00-00', 2, '0000-00-00', null);
					}
					if($staffDetail['id_package'] == 2 || $staffDetail['id_package'] == 5){
				
						$stfBonus->newStaffbonus($k5, 3, "Cycle".$idCycle." Bonus", $v5, $v5, 0, 0, $dateBegin, $dateEnd, '0000-00-00', 1, '0000-00-00', null);				
					}
					
				}
				echo ("Totally ".count($staffBonus)." staff bonus have been calculated ");
			}
		
		//d($arrWkHr);
		
		//find who is working in that time , in those shops
		// find out who are mangers
		// find out who are second in charge
	}
	
	public function teamBonusWizardNewDistributionAction(){
		$bonusRecord = new Model_Payroll_Shopgroupbonusrecord();
		$uaBonus = new Model_Payroll_Shopgroupuabonus();
		$deductLog = new Model_Payroll_Staffdeductlog();
		$stfBonus = new Model_Payroll_Staffbonus();
		$stInfo = new Model_DbTable_Roster_Staffinfo();
		$shopGroup = unserialize(NEW_SHOP_GROUP);
		$manager = unserialize(SHOP_GROUP_MANAGER);
		
		$cycle = unserialize(BONUS_CYCLE_2015);
		$tBonusList = unserialize(T_BONUS_MANAGER);
		$stfBlist = array();
		$orgBonus = array();
		$nextCheck = $this->_getParam("next");
		$periodBegin = $this->_getParam("date_begin");
		$periodEnd = $this->_getParam("date_end");
		if($nextCheck == 'yes'){
			$check = true;
			$this->view->nextCheck = $check;
		}
		$this->view->dateBegin = $periodBegin;
		$this->view->dateEnd = $periodEnd;
		
		foreach($cycle as $k2 => $v2){
			if($periodBegin >= $v2[0] && $periodEnd <= $v2[1] ){
				$cycleKey = $k2;
			}
		}
		$idCycle = $cycleKey + 1;

		foreach($shopGroup as $key => $val){
				$bonus = $bonusRecord->getBonusRecordByShopIdDate($key, $periodBegin, $periodEnd);
				if($bonus && $bonus['net_bonus'] > 0){
					$orgBonus[$bonus['shop_code']] = $bonus['net_bonus'];
					if($tBonusList[$bonus['shop_code']]){
						foreach ($tBonusList[$bonus['shop_code']] as $k => $v){	
							$stfBlist[$bonus['shop_code']][$k] = round(($v*$bonus['net_bonus']/100),2); 

						}
					}
					
				}
			
		}

		$this->view->stfBonus = $stfBlist;
		$this->view->orgBonus = $orgBonus;
		
		if(isset($_POST['submit_bonus'])){
			$totalBonus = array();
	
			foreach ($_POST['staffBonus'] as $shop => $value){
				foreach ($value as $k => $v){
					$totalBonus[$k] += $v;
				}
			}
			
			/*
			foreach ($_POST['uaBonus'] as $k => $v){
				if($v != 0){
					if(array_keys($shopGroup,$k)){
					$shopKey = array_keys($shopGroup,$k);
					$managerId = $manager[$k];
					$check = $uaBonus->getUnconfirmUABonusByShop($k, $periodBegin, $periodEnd);
					
					if($check){
						$uaBonus->updateUAbonus($check['id'], $v);
					}else{
						$uaBonus->addUAbonus($shopKey[0], $k, $periodBegin, $periodEnd, $managerId,$v);
					}
					
					}
				}
			}
			*/
			foreach ($totalBonus as $stfId => $amount){
				$staffDetail = $stInfo->getStaffinfo($stfId);
				$staffDeduct = $deductLog->getTotalDeductByStaff($stfId);
				$logDate = Model_DatetimeHelper::dateToday();
				if($staffDeduct && $staffDeduct != 0){
					$payamount = $amount + $staffDeduct;
					
					if($payamount > 0){
						echo $staffDetail['first_name']." ".$staffDetail['last_name']." Deduct:".$staffDeduct." ORG Bonus:".$amount."<br/>";
							$deductLog->addDeduct($stfId, (0-$staffDeduct), $logDate, "Cycle".$idCycle." Bonus", 'System');
						
						if($staffDetail['id_package'] == 1 || $staffDetail['id_package'] == 3 || $staffDetail['id_package'] == 4 || $staffDetail['id_package'] == 6 || $staffDetail['id_package'] == 7 || $staffDetail['id_package'] == 8){
							$amtBank = round($payamount/1.095,2);
							$amtSuper = round($payamount-$amtBank,2);
							echo $staffDetail['first_name']." ".$staffDetail['last_name']." Total Amount:".$payamount." Bank:".$amtBank." Super:".$amtSuper."<br/><br/>";
								
							$stfBonus->newStaffbonus($stfId, 3, "Cycle".$idCycle." Bonus", $payamount, 0, $amtBank, $amtSuper, $periodBegin, $periodEnd, '0000-00-00', 2, '0000-00-00', null);
						}
						if($staffDetail['id_package'] == 2 || $staffDetail['id_package'] == 5){
						
							echo $staffDetail['first_name']." ".$staffDetail['last_name']." Total Amount:".$payamount."<br/><br/>";
							$stfBonus->newStaffbonus($stfId, 3, "Cycle".$idCycle." Bonus", $payamount, $payamount, 0, 0, $periodBegin, $periodEnd, '0000-00-00', 1, '0000-00-00', null);
						}
					}else{
						echo $staffDetail['first_name']." ".$staffDetail['last_name']." Deduct:".$staffDeduct." ORG Bonus:".$amount."<br/>";
						echo $staffDetail['first_name']." ".$staffDetail['last_name']." No Bonus:".$amount." + ".$staffDeduct." <= 0<br/><br/>";
						$logDate = Model_DatetimeHelper::dateToday();
						$deductLog->addDeduct($stfId, $amount, $logDate, "Cycle".$idCycle." Bonus", 'System');
					}
					
				}else{
				
					//pay by bank
					if($staffDetail['id_package'] == 1 || $staffDetail['id_package'] == 3 || $staffDetail['id_package'] == 4 || $staffDetail['id_package'] == 6 || $staffDetail['id_package'] == 7 || $staffDetail['id_package'] == 8){
						$amtBank = round($amount/1.095,2);
						$amtSuper = round($amount-$amtBank,2);
						echo $staffDetail['first_name']." ".$staffDetail['last_name']." Total Amount:".$amount." Bank:".$amtBank." Super:".$amtSuper."<br/><br/>";
					
						$stfBonus->newStaffbonus($stfId, 3, "Cycle".$idCycle." Bonus", $amount, 0, $amtBank, $amtSuper, $periodBegin, $periodEnd, '0000-00-00', 2, '0000-00-00', null);
					}
					if($staffDetail['id_package'] == 2 || $staffDetail['id_package'] == 5){

						echo $staffDetail['first_name']." ".$staffDetail['last_name']." Total Amount:".$amount."<br/><br/>";
						$stfBonus->newStaffbonus($stfId, 3, "Cycle".$idCycle." Bonus", $amount, $amount, 0, 0, $periodBegin, $periodEnd, '0000-00-00', 1, '0000-00-00', null);
					}
				}
			}
			
			//$url = "staff/team-bonus-wizard-confirm/date_begin/".$periodBegin."/date_end/".$periodEnd."/next/yes";
			//$this->_redirect($url);
		}
	}
	
	
	public function teamBonusSetUabonusAction(){
		$bonusRecord = new Model_Payroll_Shopgroupbonusrecord();
		$uaBonus = new Model_Payroll_Shopgroupuabonus();
		$stfDetail = new Model_DbTable_Roster_Stafflogindetail();
		$stfBonus = new Model_Payroll_Staffbonus();
		$cycles = unserialize(BONUS_CYCLE_2015);
		$stInfo = new Model_DbTable_Roster_Staffinfo();
		$shopGroup = unserialize(NEW_SHOP_GROUP);
		$manager = unserialize(SHOP_GROUP_MANAGER);
		$shopMatch = unserialize(ARR_GROUP_SHOPS);
		$ts = new Model_DbTable_Roster_Timesheet();
		
		$dateBegin = $this->_getParam("date_begin");
		$dateEnd = $this->_getParam("date_end");
		
		foreach($cycles as $k2 => $v2){
			if($dateBegin >= $v2[0] && $dateEnd <= $v2[1] ){
				$cycleKey = $k2;
			}
		}
		$idCycle = $cycleKey + 1;
		
		if(isset($_POST['submit'])){
			$password = $_POST['password'];
			$arrStaff = array();
			$stfId = $stfDetail->checkPasswordCorrect(Model_EncryptHelper::hashsha(trim($password)));
			if($stfId['id'] == 337){
				$unsetBonus = $uaBonus->listAll();
			}else{
				$unsetBonus = $uaBonus->getUABonusByManagerDate($stfId['id'], $dateBegin, $dateEnd);
			}
			$this->view->unsetUabonus = $unsetBonus;
			
			foreach($unsetBonus as $k => $v){
				foreach ($shopMatch[$v['shop_id']] as $k2 => $v2){
					$tsList = $ts->listConfirmedShiftByDateByShop($v2, $dateBegin, $dateEnd);
					foreach($tsList as $line){
						if($line['confirm_shift_end'] - $line['confirm_shift_begin'] > 0){
							$arrStaff[$v['shop_id']][$line['id_staff']] = $line['id_staff'];
						}
						
					}
				}
			
			}
			$this->view->staffList = $arrStaff;
		}
		
		if(isset($_POST['submit_bonus'])){
			$tmpfinalPay = array();
			$finalPay = array();
			if(!empty($_POST['shopB1'])){
				foreach ($_POST['shopB1'] as $shopId => $id){
					if(!empty($id)){
						$tmpfinalPay[$shopId][] = array($id,$_POST['shopReason1'][$shopId]);
					}	
				
				}
			}
			
			if(!empty($_POST['shopB2'])){
				foreach ($_POST['shopB2'] as $shopId => $id){
					if(!empty($id)){
						$tmpfinalPay[$shopId][] = array($id,$_POST['shopReason2'][$shopId]);
					}
			
				}
			}
			
			foreach ($tmpfinalPay as $key => $value){
				$stf = "";
				foreach ($value as $reason){
					$stf .= $reason[0].",".$reason[1].",";
				}
				$stf = substr($stf,0,-1);
				$finalPay[$key] = $stf;
			}
			
			foreach ($finalPay as $k => $v){
				$uaBonus->updateAssignStaff($k, $v);
			}
			
		}
	}
	
	public function teamBonusAutoNoticeAction(){
		$uaBonus = new Model_Payroll_Shopgroupuabonus();
		$email = new Model_Emailshandler();
		$managerEmail = unserialize(ARR_MANAGER_EMAIL);
		
		
		$uaList = $uaBonus->getUnsetBonus();
		//d($uaList);
		$mailList = array();
		foreach ($uaList as $k => $v){
			$mailList[$v['manager_id']] = $v['manager_id'];
		}
		
		foreach ($mailList as $k => $v){
			$title = "Please set Unallocated Bonus to Staff";
			$sub = "Hi Manager<br/><br/> Please set unallocated bonus to staff, otherwise it may expired<br/><br/>Use link:".WEB_IP."/staff/team-bonus-set-uabonus/";
			//d($managerEmail[$k]);
			//$email->sendActionEmail($managerEmail[$k], $title, $sub);
		}
	}
	
	
	
	public function teamBonusConfirmUabonusAction(){
		$bonusRecord = new Model_Payroll_Shopgroupbonusrecord();
		$uaBonus = new Model_Payroll_Shopgroupuabonus();
		$stfDetail = new Model_DbTable_Roster_Stafflogindetail();
		$stfBonus = new Model_Payroll_Staffbonus();
		$cycles = unserialize(BONUS_CYCLE_2015);
		$stInfo = new Model_DbTable_Roster_Staffinfo();
		$shopGroup = unserialize(NEW_SHOP_GROUP);
		$manager = unserialize(SHOP_GROUP_MANAGER);
		$shopMatch = unserialize(ARR_GROUP_SHOPS);
		$ts = new Model_DbTable_Roster_Timesheet();
	
		$dateBegin = $this->_getParam("date_begin");
		$dateEnd = $this->_getParam("date_end");
	
		foreach($cycles as $k2 => $v2){
			if($dateBegin >= $v2[0] && $dateEnd <= $v2[1] ){
				$cycleKey = $k2;
			}
		}
		$idCycle = $cycleKey + 1;
		
		$this->view->payroll = $idCycle;
		$this->view->dateStart = $dateBegin;
		$this->view->dateEnd = $dateEnd;
		
		
		$arrResult = array();

		$unconfimUa = $uaBonus->getUABonusPeriod($dateBegin, $dateEnd);
			foreach ($unconfimUa as $k3 => $v3){
				if(!empty($v3['assign_staff'])){
					$stf = explode(",", $v3['assign_staff']);
					if(count($stf) == 6){
						$arrResult[$v3['shop_code']][$stf[0]]['amount'] = $v3['amount']/3;
						$arrResult[$v3['shop_code']][$stf[2]]['amount'] = $v3['amount']/3;
						$arrResult[$v3['shop_code']][$stf[4]]['amount'] = $v3['amount']/3;
						$arrResult[$v3['shop_code']][$stf[0]]['reason'] = $stf[1];
						$arrResult[$v3['shop_code']][$stf[2]]['reason'] = $stf[3];
						$arrResult[$v3['shop_code']][$stf[4]]['reason'] = $stf[5];
						$arrResult[$v3['shop_code']][$stf[0]]['ua_id'] = $v3['id'];
						$arrResult[$v3['shop_code']][$stf[2]]['ua_id'] = $v3['id'];
						$arrResult[$v3['shop_code']][$stf[4]]['ua_id'] = $v3['id'];
					}elseif(count($stf) == 4){
						$arrResult[$v3['shop_code']][$stf[0]]['amount'] = $v3['amount']/2;
						$arrResult[$v3['shop_code']][$stf[2]]['amount'] = $v3['amount']/2;
						$arrResult[$v3['shop_code']][$stf[0]]['reason'] = $stf[1];
						$arrResult[$v3['shop_code']][$stf[2]]['reason'] = $stf[3];
						$arrResult[$v3['shop_code']][$stf[0]]['ua_id'] = $v3['id'];
						$arrResult[$v3['shop_code']][$stf[2]]['ua_id'] = $v3['id'];
					}elseif(count($stf) <= 2){
						$arrResult[$v3['shop_code']][$stf[0]]['amount'] = $v3['amount'];
						$arrResult[$v3['shop_code']][$stf[0]]['reason'] = $v3['id'];
						$arrResult[$v3['shop_code']][$stf[0]]['ua_id'] = $v3['id'];
					}
					
				}
			}
		$this->view->result = $arrResult;
		
		if(isset($_POST['submit'])){
			$ua = $_POST['ua'];
			$action = $_POST['action'];
			$finalPay = array();
			$rejectArr = array();
			foreach ($action as $k => $v){
				if($v == 1){
					$uaBonus->confirmUabonus($k,'accept');
					foreach($ua[$k] as $stfId => $amount){
						$finalPay[$stfId] += $amount;
					}
				}else{
					 $rejectArr[$k] = $ua[$k];
				}
				
			}
			foreach ($rejectArr as $k => $v){
				$uaBonus->confirmUabonus($k, 'reject');
				$shopManager = unserialize(SHOP_GROUP_MANAGER);
				$managerEmail = unserialize(ARR_MANAGER_EMAIL);
				$reason = $_POST['reason'];
				$email = new Model_Emailshandler();
				$shopCode = $uaBonus->getUABonusById($k);
				$mailbody = "Hi Manager <br/><br/>".$shopCode." U.A bonus is rejectd <br/><br/> Reason: ".$reason[$k]." <br/><br/> Please reset bonus <br/><br/> Any problems please call Simon or Will<br/><br/>"; 
				echo "Will sent email to ".$managerEmail[$shopManager[$shopCode]]."<br/>";
				echo $mailbody;
				
				$email->sendActionEmail($managerEmail[$shopManager[$shopCode]], $shopCode.' U.A Bonus is rejected', $mailbody);
				
			}
			
			foreach ($finalPay as $stfId => $amount){
			$paytype = $stInfo->getStaffinfo($stfId);
				if($paytype['id_package'] == 1 || $paytype['id_package'] == 3 || $paytype['id_package'] == 4 || $paytype['id_package'] == 6 || $paytype['id_package'] == 7 || $paytype['id_package'] == 8){
					$amtBank = round($amount/1.095,2);
					$amtSuper = round($amount-$amtBank,2);
					$bonusCheck = $stfBonus->getBonusByIdDate($stfId, $dateBegin, $dateEnd);
					if($bonusCheck){
						$amtBank = round($bonusCheck['amt_bank_bonus'] + $amtBank,2);
						$amtSuper = round($bonusCheck['amt_bonus_super'] + $amtSuper,2);
						$amount = round($bonusCheck['amt_total_bonus']+ $amount,2);
						
						echo "Staff:".$paytype['first_name']." ".$paytype['last_name']." Bank:".$amtBank." Super:".$amtSuper." Total:".$amount."<br/>";
						//$stfBonus->updateBonus($bonusCheck['id_bonus'],$amount,0,$amtBank, $amtSuper);
					}else{
						echo "Staff:".$paytype['first_name']." ".$paytype['last_name']." Bank:".$amtBank." Super:".$amtSuper." Total:".$amount."<br/>";
						//$stfBonus->newStaffbonus($stfId, 3, "Cycle".$idCycle." Bonus", $amount, 0, $amtBank, $amtSuper, $dateBegin, $dateEnd, '0000-00-00', 2, '0000-00-00', null);
					}
					
				}
				if($paytype['id_package'] == 2 || $paytype['id_package'] == 5){
					$bonusCheck = $stfBonus->getBonusByIdDate($stfId, $dateBegin, $dateEnd);
					if($bonusCheck){
						$amount = round($bonusCheck['amt_total_bonus']+ $amount,2);
						echo "Staff:".$paytype['first_name']." ".$paytype['last_name']."Total:".$amount."<br/>";
						//$stfBonus->updateBonus($bonusCheck['id_bonus'],$amount,$amount,0,0);
					}else{
						echo "Staff:".$paytype['first_name']." ".$paytype['last_name']."Total:".$amount."<br/>";
						//$stfBonus->newStaffbonus($stfId, 3, "Cycle".$idCycle." Bonus", $amount, $amount, 0, 0, $dateBegin, $dateEnd, '0000-00-00', 1, '0000-00-00', null);
					}
					
				}
			}
		}
	
	}
	
	
	
	/**
	 * This function is last step for confirm shop bonus
	 @author leo
	 */
	public function teamBonusWizardSummaryAction(){
		$bos = new Model_Payroll_Shopgroupbonus();
		$bonusRecord = new Model_Payroll_Shopgroupbonusrecord();
		$carryBonus = new Model_Payroll_Shopgroupcarrybonus();
		$shopGroup = unserialize(ARR_SHOP_GROUP);
		$cycle = unserialize(BONUS_CYCLE_2015);
		
		
		$nextCheck = $this->_getParam("next");
		$periodBegin = $this->_getParam("date_begin");
		$periodEnd = $this->_getParam("date_end");
		if($nextCheck == 'yes'){
			$check = true;
			$this->view->nextCheck = $check;
		}
		$this->view->dateStart = $periodBegin;
		$this->view->dateEnd = $periodEnd;
		
		foreach($cycle as $k2 => $v2){ //get current cycle key
			if($periodBegin >= $v2[0] && $periodEnd <= $v2[1] ){
				$cycleKey = $k2;
			}
			
		}
		$this->view->cycle = $cycleKey + 1;

		$nextCycleBegin = $cycle[$cycleKey + 1][0];  //get next cycle
 		$nextCycleEnd = $cycle[$cycleKey + 1][1];
		
		$bonusList = array();

		foreach($shopGroup as $key => $val){
			if($key == 1 || $key == 6 || $key == 17){
			$carryOtherLost = 0;
			$otherLost = 0;
			$tmpArr2 = array();
			$adjStockLost = $bos->getStockLostByShopByType($val, $periodBegin, $periodEnd,6);
			$tmp1 = $bos->getAllStockLostByShopByType($val, $periodBegin, $periodEnd,10);
			$tmp2 = $bos->getAllStockLostByShopByType($val, $periodBegin, $periodEnd,11);
			if(!$tmp1){
				$otherLost = 0;
			}else{
				foreach($tmp1 as $k3 => $v3){
					$otherLost += $v3['amt_total_bonus'];
				}
			}
			
			if(!$tmp2){
				$carryOtherLost = 0;
			}else{
				foreach($tmp2 as $k4 => $v4){
					$carryOtherLost += $v4['amt_total_bonus'];
				}
			}
			
			$tmpArr2['id_shop'] = $key;
			$tmpArr2['shop_code']  = $val;
			$tmpArr2['adj_stocklost'] = $adjStockLost['amt_total_bonus'];
			$totalStockLost = $adjStockLost['amt_total_bonus'];
			$totalOtherLost = $otherLost + $carryOtherLost;
			$tmpArr2['total_other_lost'] = $totalOtherLost;
			$tmpforwardBonus = $carryBonus->getCarryBonusByShopIdDate($key, $periodBegin, $periodEnd);
			$bonus = $bonusRecord->getBonusRecordByShopIdDate($key, $periodBegin, $periodEnd);
			if($bonus['final_bonus'] == 0){
				$forwardBonus = 0;
				if(!empty($tmpforwardBonus)){
					$carryBonus->addCarryBonus($key, $val, 1, $tmpforwardBonus['carry_bonus'], $nextCycleBegin, $nextCycleEnd);
				}
			}else{
				if(!$tmpforwardBonus){
					$forwardBonus = 0;
				}else{
					$forwardBonus = $tmpforwardBonus['carry_bonus'];
				}
			}
			
			
			
			$tmpArr2['carry_bonus']= $forwardBonus;
			$tmpArr2['total_stock_lost'] = $totalStockLost;
			$finalBonus = $bonus['final_bonus']+$forwardBonus;
			$tmpArr2['final_bonus'] = $bonus['final_bonus'];
			
			
			if($finalBonus == 0){
				$tmpArr2['net_bonus']  = 0;
				$tmpArr2['carry_stock_lost'] = $totalStockLost;
				$tmpArr2['carry_other_lost'] = $totalOtherLost;
			}elseif ($totalStockLost >= 0){
				if($totalOtherLost == 0){
					$tmpArr2['net_bonus']  = $finalBonus;
					$tmpArr2['carry_stock_lost'] = $totalStockLost;
					$tmpArr2['carry_other_lost'] = 0;
				}else{
					if($finalBonus+$totalOtherLost >=0){
						$tmpArr2['net_bonus'] = $finalBonus+$totalOtherLost;
						$tmpArr2['carry_stock_lost'] = $totalStockLost;
						$tmpArr2['carry_other_lost'] = 0;
					}else{
						$tmpArr2['net_bonus'] = 0;
						$tmpArr2['carry_stock_lost'] = $totalStockLost;
						$tmpArr2['carry_other_lost'] = $finalBonus+$totalOtherLost;
					}
				}
				
			}elseif(($totalStockLost+$finalBonus)>=0){
				if($totalOtherLost == 0){
					$tmpArr2['net_bonus']  = $totalStockLost+$finalBonus;
					$tmpArr2['carry_stock_lost'] = 0;
					$tmpArr2['carry_other_lost'] = 0;
				}else{
					if($totalStockLost+$finalBonus+$totalOtherLost >= 0){
						$tmpArr2['net_bonus']  = $totalStockLost+$finalBonus+$totalOtherLost;
						$tmpArr2['carry_stock_lost'] = 0;
						$tmpArr2['carry_other_lost'] = 0;
					}else{
						$tmpArr2['net_bonus']  = 0;
						$tmpArr2['carry_stock_lost'] = 0;
						$tmpArr2['carry_other_lost'] = $totalStockLost+$finalBonus+$totalOtherLost;
					}
				}
				
			}elseif(($totalStockLost+$finalBonus)<0){
					$tmpArr2['net_bonus']  = 0;
					$tmpArr2['carry_stock_lost'] = $totalStockLost+$finalBonus;
					$tmpArr2['carry_other_lost'] = $totalOtherLost;
			}
			
						
			$bonusList[] = $tmpArr2;
			}
		}
		//d($bonusList);
		$this->view->bonusList = $bonusList;
		
		if(isset($_POST['submit'])){
			$bonusList2 = array();
		
			foreach($_POST['shop_code'] as $k => $v){
				//update net bonus
				$bonusRecord->updateNetBonus($k, $periodBegin, $periodEnd, $_POST['net_bonus'][$k]);
				//add carry stock lost
				$bosCheck = $bos->getStockLostByShopByType($v, $nextCycleBegin, $nextCycleEnd, 5);
				$carryOtherCheck = $bos->getStockLostByShopByType($v, $nextCycleBegin, $nextCycleEnd, 11);
				if(!$bosCheck){
					$bos->newShopbonus($k, 5, $periodBegin."carryforwardlost", $_POST['carry_stocklost'][$k], $_POST['carry_stocklost'][$k], 0, 0, $nextCycleBegin, $nextCycleEnd, '0000-00-00', 0, '0000-00-00', 'none',$v);
				}else{
					$bos->updateAdjStockLost($bosCheck['id_bonus'], $_POST['carry_stocklost'][$k], $_POST['carry_stocklost'][$k]);
				}
				//add carry other lost
				if(!$carryOtherCheck){
					$bos->newShopbonus($k, 11, $periodBegin."carryforwardotherlost", $_POST['carry_otherlost'][$k], $_POST['carry_otherlost'][$k], 0, 0, $nextCycleBegin, $nextCycleEnd, '0000-00-00', 0, '0000-00-00', 'none',$v);
				}else{
					$bos->updateAdjStockLost($carryOtherCheck['id_bonus'], $_POST['carry_otherlost'][$k], $_POST['carry_otherlost'][$k]);
				}
			}
			
			foreach($shopGroup as $k2 => $v2){
				if($k2 == 1 || $k2 == 6 || $k2 == 17){
				$adjStockLost = $bos->getStockLostByShopIdByType($k2, $periodBegin, $periodEnd,6);
				$bonusDetail = $bonusRecord->getBonusRecordByShopIdDate($k2, $periodBegin, $periodEnd);
				$carryStock = $bos->getStockLostByShopIdByType($k2, $nextCycleBegin, $nextCycleEnd,5);
				$carryOther = $bos->getStockLostByShopIdByType($k2, $nextCycleBegin, $nextCycleEnd,11);
				$otherlost = $bos->getStockLostByShopIdByType($k2, $periodBegin, $periodEnd,10);
				$lastOtherLost = $bos->getStockLostByShopIdByType($k2, $periodBegin, $periodEnd,11);
				$cBonus = $carryBonus->getCarryBonusByShopIdDate($k2, $periodBegin, $periodEnd);
				$totalOtherlost = $otherlost['amt_total_bonus'] + $lastOtherLost['amt_total_bonus'];
				
				$tmpArr3['id_shop'] = $k2;
				$tmpArr3['shop_code']  = $v2;
				$tmpArr3['adj_stocklost'] = $adjStockLost['amt_total_bonus'];
				$tmpArr3['total_other_lost'] = $totalOtherlost;
				$tmpArr3['final_bonus'] = $bonusDetail['final_bonus'];
				$tmpArr3['carry_bonus']= $cBonus['carry_bonus'];
				$tmpArr3['net_bonus'] = $bonusDetail['net_bonus'];
				$tmpArr3['carry_stock_lost'] = $carryStock['amt_total_bonus'];
				$tmpArr3['carry_other_lost'] = $carryOther['amt_total_bonus'];
				$bonusList2[] = $tmpArr3;
				}
				
			}
			$this->view->bonusList = $bonusList2;
			//d($bonusList2);
			echo "Confirm success";
		}
		
		
	}
	
	
	/**
	 * This function is for record paid T/R bonus
	 @author leo
	 */
	public function teamBonusWizardPayAction(){
		$bos = new Model_Payroll_Shopgroupbonus();
		$bonusRecord = new Model_Payroll_Shopgroupbonusrecord();
		$carryBonus = new Model_Payroll_Shopgroupcarrybonus();
		$stf = new Model_Payroll_Staffbonus();
		$sDetail = new Model_DbTable_Roster_Stafflogindetail();
		
		$shopGroup = unserialize(ARR_SHOP_GROUP);

		if(isset($_POST['saveChange'])){
			foreach($_POST['saveChange'] as $k => $v){

				$datePaid = $_POST['paid_date'][$k];
				$password = $_POST['password'][$k];
				$idStaffRow = $sDetail->checkPasswordCorrect(Model_EncryptHelper::hashsha(trim($password)));
				
				if($idStaffRow){
					if(!empty($_POST['id_bonus'])){
						foreach($_POST['id_bonus'][$k] as $k2 => $v2){
							$idBonus = $k2;
						
							$stf->updatePaymentStatus($idBonus, $datePaid,$idStaffRow['ni']);
						}
					}
				}else{
					echo '<script>alert("Wrong Password!!");</script>';
				}
			}
		}
		
		if(isset($_POST['backToHold'])){
			foreach($_POST['backToHold'] as $key => $val){
				if(!empty($_POST['id_bonus'])){
					foreach($_POST['id_bonus'][$key] as $key2 => $val2){
						$idBonus = $key2;
					
						$stf->backToHoldStatus($idBonus);
					}
				}
			}
		}
		
		
	}
	
	/**
	 * This function is for allocate a planning date for display/pay
	 * will not release to staff if not confirm
	 @author leo
	 */
	public function teamBonusWizardConfirmAction(){
		$bos = new Model_Payroll_Shopgroupbonus();
		$bonusRecord = new Model_Payroll_Shopgroupbonusrecord();
		$carryBonus = new Model_Payroll_Shopgroupcarrybonus();
		//$uaBonus = new Model_Payroll_Shopgroupuabonus();
		$stf = new Model_Payroll_Staffbonus();
		$shopGroup = unserialize(ARR_SHOP_GROUP);

		$payrollCycle = unserialize(PAYROLL_CYCLE_SELECT);
		$nextCheck = $this->_getParam("next");
		$periodBegin = $this->_getParam("date_begin");
		$periodEnd = $this->_getParam("date_end");
		if($nextCheck == 'yes'){
			$check = true;
			$this->view->nextCheck = $check;
		}
		$this->view->dateStart = $periodBegin;
		$this->view->dateEnd = $periodEnd;
		
		if(isset($_POST['confirm'])){
			$stfList = $stf->listPeriodBonus($periodBegin,$periodEnd);
			//$uaList = $uaBonus->getUnconfirmUABonus($periodBegin,$periodEnd);
			$paydate = $_POST['payroll_date'];
			/*
			if($uaList){
				foreach ($uaList as $k => $v){
					$uaBonus->updateExpirePayDate($v['id'], $_POST['display_date'], $payrollCycle[$paydate][1]);
				}
			}
			*/
			foreach($stfList as $k => $v){
				
				$stf->updateDisplayPayDate($v['id_bonus'], $_POST['display_date'], $payrollCycle[$paydate][1]);
			}
			
			
			
			$url = "/staff/team-bonus-wizard-all-summary/date_begin/".$periodBegin."/date_end/".$periodEnd;
			$this->_redirect($url);
		}
		
	}
	
	/**
	 * This function is for change/release/ teambonus
	 @author leo
	 */
	public function teamBonusWizardAllSummaryAction(){
		$bos = new Model_Payroll_Shopgroupbonus();
		$bonusRecord = new Model_Payroll_Shopgroupbonusrecord();
		$carryBonus = new Model_Payroll_Shopgroupcarrybonus();
		$stf = new Model_Payroll_Staffbonus();
		$shopGroup = unserialize(ARR_SHOP_GROUP);
		$payrollCycle = unserialize(PAYROLL_CYCLE_SELECT);

		
		
		if(isset($_POST['saveChange'])){
			foreach($_POST['saveChange'] as $k => $v){
			
				if(!empty($_POST['check_delay'])){	//update pay_date
					foreach($_POST['check_delay'][$k] as $k2 => $v2){
						$idBonus = $k2;
						$datePay = $_POST['date_delay'][$k][$k2];
						$stf->updatePaymethodStatusDate($idBonus, $payrollCycle[$datePay][1]);
	
					}
				}
				if(!empty($_POST['check_release'])){ //update display_date
					foreach($_POST['check_release'][$k] as $k2 => $v2){
						$idBonus = $k2;
						$dateRelease = $_POST['date_release'][$k][$k2];
						$stf->updateDisplayStatusDate($idBonus, $dateRelease);
					}
				}
				if(!empty($_POST['check_cancel'])){  //cancel bonus
					foreach($_POST['check_cancel'][$k] as $k2 => $v2){
						$idBonus = $k2;
						$cancelReason = $_POST['cancel_reason'][$k][$k2];
						$stf->updateCancelStatus($idBonus, $cancelReason);
				
					}
				}
				if(!empty($_POST['pay_date_check'])){  //update confirm_date
					foreach($_POST['pay_date_check'][$k] as $k2 => $v2){
						$idBonus = $k2;
						$datePaid = $_POST['pay_date'][$k][$k2];
						$stf->updateConfirmPaydate($idBonus, $payrollCycle[$datePaid][1]);
					}
				}
				
				if(!empty($_POST['add_comment'])){ //update hold comment
					foreach($_POST['add_comment'][$k] as $k2 => $v2){
						$idBonus = $k2;
						$comment = $_POST['comment'][$k];
						$stf->updateHoldReason($idBonus, $comment);
					}
				}
				
			}
		}
	
	}
	
	
	/**
	 * @tod o0Norman What is this
	 * Send PAYG
	 * 
	 */
	public function sendingEmailAction(){
		set_time_limit(0);
		ob_start();
		
		date_default_timezone_set("Australia/Melbourne");
		
		
		$fh = new Model_Fileshandler();
		//$res = $fh->readStaffEmail("AGFILE");
		//$res = array_chunk($res,6);
		$fdCot = 0;
		$mail = new Model_Emailshandler();
		$staff = new Model_DbTable_Roster_Staffinfo(Zend_Registry::get('db_remoteapp'));
		
		$tCot = 0;
		
		$mailBody = "
		Dear Staff, This is your PAYG Payment Summary for Year 2014-2015.<br />
		
		Please find detail in Attached File.<br />
		
		If you have any problems, please contact headoffice. Thank you <br/>
				
		Best Regards
		
		";
		
		$fileName = "payg_2015.csv";
		$fl = fopen(getcwd()."/PAYG/".$fileName,"r");
		while(($lineData = fgetcsv($fl,1024))!=false){

			$arrName = explode(",",$lineData[0]);

			$lastName = trim($arrName[0]);
			$firstName = trim($arrName[1]);

		  if(!empty($lastName) && !empty($firstName)){
				
				$year = date("Y");
				$attachName = $lastName.$firstName.$year.".pdf";
				if($firstName == 'Makayla'){
					$email = 'makayladcosta7@gmail.com';
						
				}else{
					$staffInfo = $staff->getStaffInfoByName($lastName,$firstName);
					if(count($staffInfo == 1)){
						$email = $staffInfo[0]['email_staff'];
					}else{
						echo "Double Name:".$lastName." ".$firstName."<br/>";
							$email = Null;
					}
				}

				$fileFd = "";
				$notFd = 0;
			

				if(!file_exists(getcwd()."/PAYG/".$attachName)){
					$fileFd = "NOTFD";
					$notFd ++;
				}else{
					$fdCot++;
					if($email){	

						$subject = "Dear ".$lastName." ".$firstName." Your 2014-2015 PAYG Summary is Here";

						$testEmail = "Email:".$email."<br/>";
						$mail->sendAttachEmail($email, $subject, $mailBody,getcwd()."/PAYG/",$attachName,"payroll@phonecollection.com.au");
					
						//sleep(5);
						echo $email."  -> ".$attachName."-> ".$fileFd."<br />";
						$tCot++;
		
					}
				}
			//phonecollection.au@gmail.com
					
			}
		
		}
		echo "Total Lost:".$notFd."<br/>";
		echo "Match:".$fdCot."<br/>";
		echo "Total:".$tCot;
	} 
	
	public function getSalesManAction(){
		
		$shop = $this->_getParam("shop");

		$aStaff = Model_Aposinitnew::initAposStaff($shop);
	
		$sStaff = new Model_DbTable_Roster_Salesmandetail(Zend_Registry::get('db_remoteapp'));		
		
		$sList = $aStaff->getAllSalesmanShop();
		
		foreach($sList as $k => $v){
			echo $v["SAL_CODE"];
			if(!($sStaff->getSalesMan(trim($v["SAL_CODE"]), $shop))){
				
				$sStaff->addSalesmandetail($shop,trim($v["SAL_CODE"]),0);			

			}
		}
		//var_dump($sList);
	}
	
	public function getSalesManCircleAction(){
		
		$arrShop = unserialize(ARR_APOS_NEW_SHOP_MAPPING);
		foreach($arrShop as $k => $v){
			Model_System_Downloadhelper::downloadUrl("http://localhost/staff/get-sales-man/shop/".$k);
			echo "DONE<br />";
		}
		
	}
	
	public function matchSalesManAction(){
		
		$sStaff = new Model_DbTable_Roster_Salesmandetail(Zend_Registry::get('db_remoteapp'));
		
		if($_POST){
				
			foreach ($_POST['id'] as $k => $v){
		
				if($v!=""){
					$sStaff->updateSalesId($k, $v);
				}
			}
		
		}
		
		$rows = $sStaff->unmatchSalesMan();
		
		$this->view->arrRes = $rows;
		

	}
	
	public function calStaffPerformanceAction(){
		
		if($_POST){
		
			$this->_redirect("/staff/cal-staff-performance/shop/".$_POST["shop"]."/date_begin/".$_POST["date_begin"]."/date_end/".$_POST["date_end"]);	
		}
		
		$shop = $this->_getParam("shop");
		$dateBegin =  $this->_getParam("date_begin");
		$dateEnd =  $this->_getParam("date_end");
		
		$intDateBegin = Model_DatetimeHelper::tranferToInt($dateBegin);
		$intDateEnd = Model_DatetimeHelper::tranferToInt($dateEnd);
		
		$this->view->shop = $shop;
		$this->view->dateBegin = $dateBegin;
		$this->view->dateEnd = $dateEnd;
		
		$invApos = Model_Aposinitnew::initAposInvoice($shop);
		
		$ts = new Model_DbTable_Roster_Timesheet(Zend_Registry::get('db_remoteapp'));
		$sales = new Model_DbTable_Roster_Salesmandetail(Zend_Registry::get('db_remoteapp'));
		
		
		$salesList = $invApos->getSaleManSales($dateBegin,$dateEnd);
		$qtyList = $invApos->getSaleManQty($dateBegin, $dateEnd);
		//var_dump($salesList);
		$arrRes = array();
		$aveArr = array();
		$arrRes2 = array();
		$arrSph = array();
		
		foreach($salesList as $k => $v){
			
			$totalHour = 0;
			
			$positionDash = strrpos(trim($v["SAL_CODE"]),"-");
			$idStaff = '';
			if($positionDash > 0){
				$idStaff = (int) substr(trim($v["SAL_CODE"]),0,$positionDash);
			}
			else{
				$idRow = $sales->getSalesMan($v["SAL_CODE"],$shop);
					
				$idStaff = $idRow["id_staff"];
			}
			
			if(trim($v['SAL_CODE']) == '388-JOHN'){
				//d($idStaff);
			}
				
			
			$units = 0;
			$trans = 0;
			
			$sph = 0; // sales pre hour
			$tph = 0; // transaction pre hour
			$uph = 0; // unit pre hour
			$upt = 0; // unit pre transaction
			$spt = 0; // sales pre transaction
			// bundle 
			//discount rate 
			//total discount rate
			
			
			if($idStaff > 0){
				//var_dump($idStaff, $intDateBegin, $intDateEnd,$shop);
			$totalHour = $ts->totalWorkingHours($idStaff, $intDateBegin, $intDateEnd,$shop);
			}
			
			if($totalHour >0){
			//echo $v["SAL_CODE"]." - \$".$v["SALES"]." - ".$totalHour." - ".round($v["SALES"]/$totalHour,2)."<br />";
			$sph = round($v["SALES"]/$totalHour,2);
			}
			
			foreach($qtyList as $k2 => $v2){
				if($v2["SAL_CODE"] == $v["SAL_CODE"]){
					
					$units = $v2["QTYS"];
					$trans = $v2["COUNTS"];
					if($totalHour >0){
						
						$uph = round($units/$totalHour,2);
						$tph = round($trans/$totalHour,2);
					}					
					
					$spt = round($v["SALES"]/$trans,2);
					$upt = round($units/$trans,2);
					
					
				}
				
			}

			$arrRes[] =  array($idStaff,$v["SAL_CODE"],$v["SALES"],$totalHour,$units,$trans);
			$aveArr[] = $v["SALES"];
			$arrRes2[] = array($idStaff,$v["SAL_CODE"],$sph,$uph,$tph,$spt,$upt);
			$arrSph[] = $sph;
		}
		array_multisort($aveArr,SORT_DESC,$arrRes);
		array_multisort($arrSph,SORT_DESC,$arrRes2);
		
		$this->view->arrRes = $arrRes;
		$this->view->arrRes2 = $arrRes2;
		
		//$this->view->upt = $qtyList;
		//var_dump($qtyList);
	}
	
	public function calStaffPerformanceAllAction(){
		
		$dateBegin =  $this->_getParam("date_begin");
		$dateEnd =  $this->_getParam("date_end");	
		
		$intDateBegin = Model_DatetimeHelper::tranferToInt($dateBegin);
		$intDateEnd = Model_DatetimeHelper::tranferToInt($dateEnd);
		
		$ts = new Model_DbTable_Roster_Timesheet(Zend_Registry::get('db_remoteapp'));
		$sales = new Model_DbTable_Roster_Salesmandetail(Zend_Registry::get('db_remoteapp'));
		
		
		$arrRes = array();
		$aveArr = array();
		$arrRes2 = array();
		$arrSph = array();
		
		
		$shopArr = unserialize(ARR_SHOP_ACTIVE);
		
		foreach($shopArr as $shop){
			

			$invApos = Model_Aposinitnew::initAposInvoice($shop);

			$salesList = $invApos->getSaleManSales($dateBegin,$dateEnd);
			$qtyList = $invApos->getSaleManQty($dateBegin, $dateEnd);
			
			foreach($salesList as $k => $v){
			
				$totalHour = 0;
			$positionDash = strrpos(trim($v["SAL_CODE"]),"-");
			$idStaff = '';
			if($positionDash > 0){
				$idStaff = (int)substr(trim($v["SAL_CODE"]),0,$positionDash);
			}
			else{
				$idRow = $sales->getSalesMan($v["SAL_CODE"],$shop);
					
				$idStaff = $idRow["id_staff"];
			}
			
			
			
				$units = 0;
				$trans = 0;
			
				$sph = 0; // sales pre hour
				$tph = 0; // transaction pre hour
				$uph = 0; // unit pre hour
				$upt = 0; // unit pre transaction
				$spt = 0; // sales pre transaction
				// bundle
				//discount rate
				//total discount rate
			
			
				if($idStaff > 0){
					//var_dump($idStaff, $intDateBegin, $intDateEnd,$shop);
					$totalHour = $ts->totalWorkingHours($idStaff, $intDateBegin, $intDateEnd,$shop);
				}
			
				//if($totalHour >0){
					//echo $v["SAL_CODE"]." - \$".$v["SALES"]." - ".$totalHour." - ".round($v["SALES"]/$totalHour,2)."<br />";
				//	$sph = round($v["SALES"]/$totalHour,2);
				//}
			
				foreach($qtyList as $k2 => $v2){
					if($v2["SAL_CODE"] == $v["SAL_CODE"]){
			
						$units = $v2["QTYS"];
						$trans = $v2["COUNTS"];
						if($totalHour >0){
			
							$uph = round($units/$totalHour,2);
							$tph = round($trans/$totalHour,2);
						}
			
						$spt = round($v["SALES"]/$trans,2);
						$upt = round($units/$trans,2);
			
			
					}
			
				}
			
				$arrRes[] =  array($idStaff,$v["SAL_CODE"],$v["SALES"],$totalHour,$units,$trans);
				$aveArr[] = $v["SALES"];
				//$arrRes2[] = array($idStaff,$v["SAL_CODE"],$sph,$uph,$tph,$spt,$upt);
				//$arrSph[] = $sph;
			}			
			
		}
		//echo "<pre>";		
		//var_dump ($arrRes);
		//echo "</pre>";		
		$arrIdStaff = array();
		$arrResAll = array();
		$arrTSales = array();
		
		foreach($arrRes as $line){
		//echo "<pre>";		
		//var_dump ($arrIdStaff);
		
		//echo $line[0];
		
		//echo "</pre>";	
			
			
			
			$idStaff = array_search($line[0], $arrIdStaff);
			
			if($idStaff=== false){
				//add new 
				$idStaff = $line[0];
				
				$arrIdStaff[$idStaff] = $idStaff;
				$arrTSales[$idStaff] =  $line[2];
				
				
				$arrResAll[$idStaff]['name'] = $line[1];
				if($line[0]==""){
					$arrResAll[$idStaff]['name']="-";
				}
				$arrResAll[$idStaff]['sales'] = $line[2];
				
				
				$arrResAll[$idStaff]['total_hour'] = $line[3];
				$arrResAll[$idStaff]['total_unit'] = $line[4];
				$arrResAll[$idStaff]['total_trans'] = $line[5];
			}
			else{
				
				//echo "-------".$line[0];
				//$arrResAll[$idStaff]['name'] = $line[1];
				$arrResAll[$idStaff]['sales'] += $line[2];
				$arrTSales[$idStaff] +=  $line[2];
				$arrResAll[$idStaff]['total_hour'] += $line[3];
				$arrResAll[$idStaff]['total_unit'] += $line[4];
				$arrResAll[$idStaff]['total_trans'] += $line[5];				
				
			}
			
		}
	
		//echo "<pre>";		
		//var_dump ($arrResAll);
		//echo "</pre>";
		
		
		array_multisort($arrTSales,SORT_DESC,$arrResAll);

		$arrResAll2 = array();
		$arrSph = array();
		
		foreach($arrResAll as $k2 => $v2){
			if( $v2['total_hour'] > 0 && $v2['total_trans'] > 0 ){

				$arrResAll2[$k2]['name'] = $v2['name'];
				$arrResAll2[$k2]['sph'] = round($v2['sales']/$v2['total_hour'],2);  
				$arrResAll2[$k2]['tph'] = round($v2['total_trans']/$v2['total_hour'],2);
				$arrResAll2[$k2]['spt'] = round($v2['sales']/$v2['total_trans'],2);
				$arrResAll2[$k2]['upt'] = round($v2['total_unit']/$v2['total_trans'],2);
				$arrResAll2[$k2]['total_hour'] = $v2['total_hour'];
				$arrResAll2[$k2]['total_trans'] = $v2['total_trans'];
				
				$arrSph[$k2] = round($v2['sales']/$v2['total_hour'],2);
			}
		}
		array_multisort($arrSph,SORT_DESC,$arrResAll2);
		
		$this->view->arrResAll = $arrResAll;
		$this->view->arrResAll2 = $arrResAll2;
		
	}
	
	public function calStaffPerformanceShopsAction(){
	
		$dateBegin =  $this->_getParam("date_begin");
		$dateEnd =  $this->_getParam("date_end");
		$arrShop = $this->_getParam("shop");
	
		$intDateBegin = Model_DatetimeHelper::tranferToInt($dateBegin);
		$intDateEnd = Model_DatetimeHelper::tranferToInt($dateEnd);
	
		$ts = new Model_DbTable_Roster_Timesheet(Zend_Registry::get('db_remoteapp'));
		$sales = new Model_DbTable_Roster_Salesmandetail(Zend_Registry::get('db_remoteapp'));
	
	
		$arrRes = array();
		$aveArr = array();
		$arrRes2 = array();
		$arrSph = array();
	
		//$shopArr = array("ADPC","BBPC","BHPC","BSPC","BSIC","CBPC","CLPC","EPPC","KCPC","NLPC","PMPC","SLIC","WBPC","WBIC","WLIC","WGIC","WGPC","CSIC","CLIC","DCIC","PMIC","BSXP","FGIC","HPIC");
	
		$shopArr = unserialize(base64_decode($arrShop));
		foreach($shopArr as $shop){
				
	
			$invApos = Model_Aposinitnew::initAposInvoice($shop);
	
			$salesList = $invApos->getSaleManSales($dateBegin,$dateEnd);
			$qtyList = $invApos->getSaleManQty($dateBegin, $dateEnd);
				
			foreach($salesList as $k => $v){
					
				$totalHour = 0;
				
				$positionDash = strrpos(trim($v["SAL_CODE"]),"-");
				$idStaff = '';
				if($positionDash > 0){
					$idStaff = (int) substr(trim($v["SAL_CODE"]),0,$positionDash);
				}
				else{
					$idRow = $sales->getSalesMan($v["SAL_CODE"],$shop);
						
					$idStaff = $idRow["id_staff"];
				}
				
				
				
				$units = 0;
				$trans = 0;
					
				$sph = 0; // sales pre hour
				$tph = 0; // transaction pre hour
				$uph = 0; // unit pre hour
				$upt = 0; // unit pre transaction
				$spt = 0; // sales pre transaction
				// bundle
				//discount rate
				//total discount rate
					
					
				if($idStaff > 0){
					//var_dump($idStaff, $intDateBegin, $intDateEnd,$shop);
					$totalHour = $ts->totalWorkingHours($idStaff, $intDateBegin, $intDateEnd,$shop);
				}
					
				//if($totalHour >0){
				//echo $v["SAL_CODE"]." - \$".$v["SALES"]." - ".$totalHour." - ".round($v["SALES"]/$totalHour,2)."<br />";
				//	$sph = round($v["SALES"]/$totalHour,2);
				//}
					
				foreach($qtyList as $k2 => $v2){
					if($v2["SAL_CODE"] == $v["SAL_CODE"]){
							
						$units = $v2["QTYS"];
						$trans = $v2["COUNTS"];
						if($totalHour >0){
								
							$uph = round($units/$totalHour,2);
							$tph = round($trans/$totalHour,2);
						}
							
						$spt = round($v["SALES"]/$trans,2);
						$upt = round($units/$trans,2);
							
							
					}
						
				}
					
				$arrRes[] =  array($idStaff,$v["SAL_CODE"],$v["SALES"],$totalHour,$units,$trans);
				$aveArr[] = $v["SALES"];
				//$arrRes2[] = array($idStaff,$v["SAL_CODE"],$sph,$uph,$tph,$spt,$upt);
				//$arrSph[] = $sph;
			}
				
		}
		//echo "<pre>";
		//var_dump ($arrRes);
		//echo "</pre>";
		$arrIdStaff = array();
		$arrResAll = array();
		$arrTSales = array();
	
		foreach($arrRes as $line){
			//echo "<pre>";
			//var_dump ($arrIdStaff);
	
			//echo $line[0];
	
			//echo "</pre>";
				
				
				
			$idStaff = array_search($line[0], $arrIdStaff);
				
			if($idStaff=== false){
				//add new
				$idStaff = $line[0];
	
				$arrIdStaff[$idStaff] = $idStaff;
				$arrTSales[$idStaff] =  $line[2];
	
	
				$arrResAll[$idStaff]['name'] = $line[1];
				if($line[0]==""){
					$arrResAll[$idStaff]['name']="-";
				}
				$arrResAll[$idStaff]['sales'] = $line[2];
	
	
				$arrResAll[$idStaff]['total_hour'] = $line[3];
				$arrResAll[$idStaff]['total_unit'] = $line[4];
				$arrResAll[$idStaff]['total_trans'] = $line[5];
			}
			else{
	
				//echo "-------".$line[0];
				//$arrResAll[$idStaff]['name'] = $line[1];
				$arrResAll[$idStaff]['sales'] += $line[2];
				$arrTSales[$idStaff] +=  $line[2];
				$arrResAll[$idStaff]['total_hour'] += $line[3];
				$arrResAll[$idStaff]['total_unit'] += $line[4];
				$arrResAll[$idStaff]['total_trans'] += $line[5];
	
			}
				
		}
	
		//echo "<pre>";
		//var_dump ($arrResAll);
		//echo "</pre>";
	
	
		array_multisort($arrTSales,SORT_DESC,$arrResAll);
	
		$arrResAll2 = array();
		$arrSph = array();
	
		foreach($arrResAll as $k2 => $v2){
			if( $v2['total_hour'] > 0 && $v2['total_trans'] > 0 ){
	
				$arrResAll2[$k2]['name'] = $v2['name'];
				$arrResAll2[$k2]['sph'] = round($v2['sales']/$v2['total_hour'],2);
				$arrResAll2[$k2]['tph'] = round($v2['total_trans']/$v2['total_hour'],2);
				$arrResAll2[$k2]['spt'] = round($v2['sales']/$v2['total_trans'],2);
				$arrResAll2[$k2]['upt'] = round($v2['total_unit']/$v2['total_trans'],2);
				$arrResAll2[$k2]['total_hour'] = $v2['total_hour'];
				$arrResAll2[$k2]['total_trans'] = $v2['total_trans'];
	
				$arrSph[$k2] = round($v2['sales']/$v2['total_hour'],2);
			}
		}
		array_multisort($arrSph,SORT_DESC,$arrResAll2);
	
		$this->view->arrResAll = $arrResAll;
		$this->view->arrResAll2 = $arrResAll2;
	
	}
	
	
	public function listStaffBonusAction(){
		
	}
	public function addBonusAction(){
		
		$idStaff = $this->_getParam("id");
		
		$periodBegin = "";
		$periodEnd = "";
		$payType = 1;
		
		$periodBegin = $this->_getParam("date_begin");
		$periodEnd = $this->_getParam("date_end");
		$payType = $this->_getParam("pay_type");
		

			
		$this->view->periodBegin = $periodBegin;
		$this->view->periodEnd = $periodEnd;
		$this->view->payType = $payType;
		
		
		
		$bType = new Model_Payroll_Staffbonustype();
		$stInfo = new Model_DbTable_Roster_Staffinfo();
		$bos = new Model_Payroll_Staffbonus();
		
		$stRow = $stInfo->getStaffinfo($idStaff);
		$this->view->stDetail = $stRow;
		$this->view->bTypeList = $bType->listAll();
		if($_POST){
			//var_dump($_POST);
			$lastId = $bos->newStaffbonus($idStaff, $_POST['bonus_type'], $_POST['detail_bonus'],$_POST['amt_total'],$_POST['amt_cash'], $_POST['amt_bank'], $_POST['amt_super'], $_POST['period_begin'], $_POST['period_end'], $_POST['pay_date'], $_POST['pay_type'], '1111-01-01',null);
			$bos->updateDisplayPayDate($lastId, $_POST['display_date'], $_POST['pay_date']);
			echo "For Staff ID: ".$idStaff." Bonus Added Success";
		}
	}
	public function editBonusAction(){
		
	}
	public function removeBonusAction(){
		
	}
	
	public function listAllBonusAction(){
		
		$this->view->pay = $this->_getParam("pay");
		$this->view->hr = $this->_getParam("hr");
		
		$bos = new Model_Payroll_Staffbonus();
		$date = $this->_getParam("date_begin");
		$dateEnd = $this->_getParam("date_end");
		
		if($_POST){
			
			if(isset($_POST['btn_release'])){
				
				if(!empty($_POST['check_release'])){
				foreach($_POST['check_release'] as $rel){
					$bos->releaseBonus($rel, $_POST['date_release'][$rel],$_POST['release_comment'][$rel]);
				}
				}
				if(!empty($_POST['check_cancel'])){
				foreach($_POST['check_cancel'] as $k => $v){
					$bos->cancelBonus($k,$_POST['release_comment'][$k]);
				}
				}
			}elseif(isset($_POST['cancel_bt'])){
				if(!empty($_POST['check_cancel'])){
					foreach($_POST['check_cancel'] as $k => $v){
					$bos->cancelBonus($k,$_POST['cancel_reason'][$k]);
					}
				}
			}elseif(isset($_POST['save_bt'])){
				if(!empty($_POST['check_delay'])){
						foreach($_POST['check_delay'] as $rev){
							$bos->releaseBonus($rev, $_POST['date_delay'][$rev],"");
					}
				}
			}
						else{
				foreach($_POST['id_bonus'] as $key => $v){	
					$bos->bonusPaid($v, $_POST['paid_date']);
				}
			}
		}
		
		$this->view->bList = $bos->listBonusByPayDate($date,$dateEnd);
		$this->view->hList = $bos->listAllHoldBonus();
		
		if($this->view->pay == "yes"){
			$this->renderScript("/staff/list-all-bonus-140407.phtml");

		}else if($this->view->hr == "yes"){
			$this->renderScript("/staff/list-all-bonus-140528.phtml");
		}
	}

	public function calStaffPerformancePublicAction(){
		
		if($_POST){
			$arrShop = base64_encode(serialize($_POST['shop_selection']));
			$dateBegin = $_POST['date_begin'];
			$dateEnd = $_POST['date_end'];
			
			$url = "http://".SERVER_IP_COMM."/staff/cal-staff-performance-shops/shop/".$arrShop."/date_begin/".$dateBegin."/date_end/".$dateEnd;
			echo $str = Model_System_Downloadhelper::downloadUrl($url);			
		}
		
	}
	
	public function importAddressAndEmailAction(){
		
		$arrPC = Model_Fileshandler::readMyobFile('EMPLOY-PC.TXT');
		$arrCash = Model_Fileshandler::readMyobFile('EMPLOY-CASH.TXT');
		$stInfo = new Model_DbTable_Roster_Staffinfo();		
		
		
	}
	
	public function importMyobFileAction(){
		
		$arrPC = Model_Fileshandler::readMyobFile('EMPLOY-PC.TXT');
		$arrCash = Model_Fileshandler::readMyobFile('EMPLOY-CASH.TXT');
		$stInfo = new Model_DbTable_Roster_Staffinfo();
		//d($arrPC);
		//d($arrCash);
		echo "<pre>";
		//var_dump($arrCash);
		echo "</pre>";
		
		
		foreach($arrCash as $k => $v){
			
			d($v);
			
			$addr = trim($v['5-Addr1-Line1']." ".$v['6--Line2']." ".$v['7--Line3']." ".$v['8--Line4']);
			
			$suburb = trim($v['9--City']);
			$state = trim($v['10--State']);
			$postCode = trim($v['11--Postcode']);
			$phone = trim($v['13--Phone#1']);
			$email1 = trim($v['17--Email']); 
			$email2 = trim($v['133-PaySlipEmail']);
			$recordID = (int)$v['126-RecordID'];
			
			$email = $email1;
			if(trim($email2)!="" && strcmp(trim($email1), trim($email2))!=0 && strpos(trim($email2), '@')>0){
				$email = $email2;
			}			
			$stLine = $stInfo->getstaffIDByRecordID($recordID,"Cash");
			
			if($stLine){
				echo "FInd ID<br />";
			$idStaff = $stLine['id_staff'];
			$infoLine = $stInfo->getStaffinfo($idStaff);
			
			if($addr!=""){
				
				$stInfo->updateAddressStaffinfo($idStaff, $addr, $suburb, $state, $postCode);
				echo "UPDATE ADDR<br />";
			}
			
			
			if(trim($infoLine['email_staff'])=="" && $email!=""){
				
				
				$stInfo->updateEmail($idStaff, $email);
				echo "UP EMAIL<br />";
			}
			
			if(trim($infoLine['mobile_staff'])=="" && $phone!=""){
				
				$stInfo->updateMobile($idStaff, $phone);
				echo "UPMOBILE ID<br />";
			}
			
			
			}
			else{
				
				echo "NOT ID<br />";
			}
			
		}
		/*
		foreach($arrPC as $k => $v){
				
			
			$rate = $v['Salary/Rate'];
				
			$stLine = $stInfo->getstaffIDByRecordID($recordID,'bank');
				
			if($stLine){
				$idStaff = $stLine['id_staff'];
				$stInfo->updateRateOnceOff($idStaff, $rate);
			}
				
		}		
		
		*/
	}

	
	/**
	 * This function is for import super info and record confirm paid
	 @author leo
	 */
	public function superSummaryAction(){
		$stfInfo = new Model_DbTable_Roster_Staffinfo();
		$sDetail = new Model_DbTable_Roster_Stafflogindetail();
		$super = new Model_Payroll_Staffsuper();
		$fl = new Model_Fileshandler();
		$tmpPeriod = $super->listAll();
		
		foreach ($tmpPeriod as $k5 => $v5){
			$period[$v5['start_date'].":".$v5['end_date']] = array($v5['start_date'],$v5['end_date']);
		}
		
		$this->view->period = $period;
		$fullist = array();
		
		if(isset($_POST['upload'])){
			if(move_uploaded_file($_FILES['file']['tmp_name'],getcwd().'/'.$_FILES['file']['name'])){
				$arr = $fl->readSuperExcel(getcwd().'/'.$_FILES['file']['name']);
			}
			$superList = array();
			$importList = array();
			$errorList = array();
			$time = preg_split("/[\s,\/]+/", $arr[8]['B']);
			if($time[0] < 10){
				$day1 = "0".$time[0];
			}else{
				$day1 = $time[0];
			}
			if($time[4] < 10){
				$day2 = "0".$time[4];
			}else{
				$day2 = $time[4];
			}
			
			$month1 = $time[1];
			$month2 = $time[5];
			$year1 = $time[2];
			$year2 = $time[6];
			$beginDate = $year1."-".$month1."-".$day1;
			$endDate = $year2."-".$month2."-".$day2;
			$sortComName = array();
			$sortPay = array();
			foreach($arr as $k => $v){
				$tmpArr = array();
				
				$sepName = explode(",", $v['B']);
				$amount = $v['C'];
				if(count($sepName)== 2){
					if($amount != 0){
					$lastName = trim($sepName[0]);
					$firstName = trim($sepName[1]);
					
					$tmpArr['last_name'] = $lastName;
					$tmpArr['first_name'] = $firstName;
					$tmpArr['start_date'] = $beginDate;
					$tmpArr['end_date'] = $endDate;
					$fullname = $firstName." ".$lastName;
					$tmpArr['amount'] = $amount;
					$rLastName = str_replace("'", "''", $lastName);
					$rFirstName = str_replace("'", "''", $firstName);
					$stfDetail = $stfInfo->getStaffInfoByName($rLastName, $rFirstName);
					
					if(count($stfDetail)<2){
						if($stfDetail){
							$tmpArr['staff_id'] = $stfDetail[0]['id_staff'];
							$tmpArr['staff_leave_date'] = $stfDetail[0]['leave_date'];
							$superList[] = $tmpArr;
							//$fullist[] = $tmpArr;
						}else{
							$errorList[] = $tmpArr;
							//$fullist[] = $tmpArr;
						}
					}else{
						$errorList[] = $tmpArr;
						//$fullist[] = $tmpArr;
					}
					}
				}
					
				
			}

			foreach($superList as $k2 => $v2){
				
				$superCheck = $super->getSuperByStaffIdDate($v2['staff_id'], $beginDate, $endDate);
				if(!$superCheck && $v2['amount'] != 0){
					$super->addSuper($v2['staff_id'], $v2['amount'], $beginDate, $endDate);
				}else{
					if($superCheck['paid_date'] == null && $v2['amount'] != 0){
						$super->updateSuper($superCheck['id'], $v2['staff_id'], $v2['amount'], $beginDate, $endDate);
					}
				}
			}
			/*
			foreach ($fullist as $value){
				echo $value['staff_leave_date']."<br>";
			}*/

			$list = $super->listPeriodSuper($beginDate, $endDate);
			foreach ($list as $k2 => $v2){
				$stfDetail = $stfInfo->getStaffinfo($v2['staff_id']);
				$tmpArr = array();
				$tmpArr['super_id'] = $v2['id'];
				$tmpArr['last_name'] = trim($stfDetail['last_name']);
				$tmpArr['first_name'] = trim($stfDetail['first_name']);
				$tmpArr['start_date'] = $v2['start_date'];
				$tmpArr['end_date'] = $v2['end_date'];
				$tmpArr['amount'] = $v2['amount'];
				$tmpArr['staff_id'] = $stfDetail['id_staff'];
				if(!$stfDetail['super_id_company']){
					$tmpArr['super_id_company'] = 'zull';
				}else{
					$tmpArr['super_id_company'] = $stfDetail['super_id_company'];
				}
				if(!$stfDetail['super_payment_method']){
					$tmpArr['super_payment_method'] = 'zull';
				}else{
					$tmpArr['super_payment_method'] = $stfDetail['super_payment_method'];
				}
				$tmpArr['super_bulk_employee_id'] = $stfDetail['super_bulk_employee_id'];
				$tmpArr['super_acc_name'] = $stfDetail['super_acc_name'];
				$tmpArr['super_acc_no'] = $stfDetail['super_acc_no'];
				$tmpArr['super_acc_bsb'] = $stfDetail['super_acc_bsb'];
				$tmpArr['super_bpay_biller_code'] = $stfDetail['super_bpay_biller_code'];
				$tmpArr['super_bpay_reference']  = $stfDetail['super_bpay_reference'];
				$tmpArr['super_paid_date'] = $v2['paid_date'];
				$tmpArr['super_paid_staff'] = $v2['paid_staff'];
				$sortComName[] = $stfDetail['super_id_company'];
				$sortPay[] = $stfDetail['super_payment_method'];
				$importList[] = $tmpArr;
			}
				
			array_multisort($sortComName,SORT_DESC,$sortPay,SORT_DESC,$importList);
			$this->view->superList = $importList;
			if($errorList){
				$this->view->errorList = $errorList;
			}
				
		}
		
		
		
		
		if(isset($_POST['add_record'])){
			foreach ($_POST['staff_name'] as $k3 => $v3){
				
				if($v3){
					$superCheck = $super->getSuperByStaffIdDate($v3, $_POST['start_date'][$k3], $_POST['end_date'][$k3]);
					
					if(!$superCheck){
						$super->addSuper($v3, $_POST['amount'][$k3], $_POST['start_date'][$k3], $_POST['end_date'][$k3]);
					}else{
						if($superCheck['paid_date'] == null){
							$super->updateSuper($superCheck['id'], $v3, $_POST['amount'][$k3], $_POST['start_date'][$k3], $_POST['end_date'][$k3]);
						}
					}
					$dateBegin = $_POST['start_date'][$k3];
					$dateEnd = $_POST['end_date'][$k3];

				}
			}
			
			/*
			$list = $super->listPeriodSuper($dateBegin, $dateEnd);
			$sortComName = array();
			$sortPay = array();
			$superList = array();
			foreach ($list as $k2 => $v2){
				$stfDetail = $stfInfo->getStaffinfo($v2['staff_id']);
				$tmpArr = array();
				$tmpArr['super_id'] = $v2['id'];
				$tmpArr['last_name'] = trim($stfDetail['last_name']);
				$tmpArr['first_name'] = trim($stfDetail['first_name']);
				$tmpArr['start_date'] = $v2['start_date'];
				$tmpArr['end_date'] = $v2['end_date'];
				$tmpArr['amount'] = $v2['amount'];
				$tmpArr['staff_id'] = $stfDetail['id_staff'];
				if(!$stfDetail['super_id_company']){
					$tmpArr['super_id_company'] = 'zull';
				}else{
					$tmpArr['super_id_company'] = $stfDetail['super_id_company'];
				}
				if(!$stfDetail['super_payment_method']){
					$tmpArr['super_payment_method'] = 'zull';
				}else{
					$tmpArr['super_payment_method'] = $stfDetail['super_payment_method'];
				}
				$tmpArr['super_bulk_employee_id'] = $stfDetail['super_bulk_employee_id'];
				$tmpArr['super_acc_name'] = $stfDetail['super_acc_name'];
				$tmpArr['super_acc_no'] = $stfDetail['super_acc_no'];
				$tmpArr['super_acc_bsb'] = $stfDetail['super_acc_bsb'];
				$tmpArr['super_bpay_biller_code'] = $stfDetail['super_bpay_biller_code'];
				$tmpArr['super_bpay_reference']  = $stfDetail['super_bpay_reference'];
				$tmpArr['super_paid_date'] = $v2['paid_date'];
				$tmpArr['super_paid_staff'] = $v2['paid_staff'];
				$sortComName[] = $stfDetail['super_id_company'];
				$sortPay[] = $stfDetail['super_payment_method'];
				$superList[] = $tmpArr;
			}
			
			array_multisort($sortComName,SORT_DESC,$sortPay,SORT_DESC,$superList);
			$this->view->superList = $superList;
			*/
		}
		
		if(isset($_POST['paid_submit'])){
			
			if(!empty($_POST['paid_date'])){
				$payDate = $_POST['pay_date'];
				$password = $_POST['password'];
				$idStaffRow = $sDetail->checkPasswordCorrect(Model_EncryptHelper::hashsha(trim($password)));
				
				if($idStaffRow){
					if(!empty($_POST['paid_date'])){

						foreach($_POST['paid_date'] as $k4 => $v4){
							foreach ($v4 as $k6 => $v6){
							$idSuper = $v6;
						
							$super->updateSuperPaidDate($idSuper, $payDate,$idStaffRow['ni']);
							}
						}
					}
				}else{
					echo '<script>alert("Wrong Password!!");</script>';
				}
			}
			
			
		}
	}
	
	
	public function listAllShopBonusAction(){
	
		$this->view->pay = $this->_getParam("pay");
		$this->view->hr = $this->_getParam("hr");
	
		$bos = new Model_Payroll_Shopgroupbonus();
		$date = $this->_getParam("date_begin");
	
		if($_POST){
	
			if(isset($_POST['btn_release'])){
	
				if(!empty($_POST['check_release'])){
					foreach($_POST['check_release'] as $rel){
						$bos->releaseBonus($rel, $_POST['date_release'][$rel],$_POST['release_comment'][$rel]);
					}
				}
				if(!empty($_POST['check_cancel'])){
					foreach($_POST['check_cancel'] as $k => $v){
						$bos->cancelShopBonus($k,$_POST['release_comment'][$k]);
					}
				}
			}elseif(isset($_POST['cancel_bt'])){
				if(!empty($_POST['check_cancel'])){
					foreach($_POST['check_cancel'] as $k => $v){
						$bos->cancelShopBonus($k,$_POST['cancel_reason'][$k]);
					}
				}
			}elseif(isset($_POST['save_bt'])){
				if(!empty($_POST['check_delay'])){
					foreach($_POST['check_delay'] as $rev){
						$bos->releaseBonus($rev, $_POST['date_delay'][$rev],"");
					}
				}
			}
			else{
				foreach($_POST['id_bonus'] as $key => $v){
					$bos->bonusPaid($v, $_POST['paid_date']);
				}
			}
		}
	
	
		$this->view->bList = $bos->listBonusByPayDate($date);
		$this->view->hList = $bos->listAllHoldBonus();
		if($this->view->pay == "yes"){
			$this->renderScript("/staff/list-all-shop-bonus-140611.phtml");
	
		}else if($this->view->hr == "yes"){
			$this->renderScript("/staff/list-all-shop-bonus-140612.phtml");
		}
	}
	/**
	 * Once Off Visa Staus , and Visa Date 
	 */
	
	public function onceOffDateVisaAction(){
		$arr = array(301,
307,
282,
204,
9,
276,
149,
340,
36,
305,
320,
280,
10,
325,
312,
328,
334,
345,
351,
115,
356,
25,
130,
30,
357,
344,
321,
143,
18,
335,
313,
151,
347,
219,
271,
349,
314,
279,
353,
297
		);
		$stInfo = new Model_DbTable_Roster_Staffinfo();
		$arrRes = array();
		foreach($arr as $idStaff){

			$stLine = $stInfo->getStaffinfo($idStaff);
			
			
			if($stLine['no_passport']!="" && Model_EncryptHelper::getSslPassword($stLine['no_passport'])!="" ){
			$arrRes[] = array($idStaff,$stLine['register_date'],Model_EncryptHelper::getSslPassword($stLine['visa_type']),Model_EncryptHelper::getSslPassword($stLine['visa_date']));
			}
			else{

				$arrRes[] = array($idStaff,$stLine['register_date']," "," ");
					
			}
			
			
		}
		
		//d($arrRes);
		$this->view->arrRes = $arrRes;
		
	}
	/**
	 * once off function , check all person who still working after 05.30 with empty passport and driver's liciense
	 */
	public function missingPassportAction(){
		
		$stInfo = new Model_DbTable_Roster_Staffinfo();
		$stList = $stInfo->listAll();
		$dateBegin = "2014-05-30";
		$dateEnd = "2014-07-11";
		
		$attRecords = new Model_DbTable_Roster_Attnrecord();
		
		foreach($stList as $staff){
			
			$idStaff = $staff['id_staff'];
			
			// check if current 
			$arrAtt = $attRecords->listRecordByStaffId($idStaff, $dateBegin, $dateEnd);
			
			if($arrAtt){
				
				if( $staff['no_passport']=="" && $staff['driver_license']=="" ){
					
				echo $idStaff.",".$staff['last_name']." ".$staff['first_name']."<br />";	
				}
			}
			
		}
		
	}
	/**
	 * New Function of Staff Automatic Leave 
	 * on 23.59 Set Staff Disable Today
	 * is the server still running on 23.59?
	 * @author Norman
	 * @version 2014-07-15
	 */
	public function autoSetLeaveAction(){
		
		// run toay 23.59
		$stInfo = new Model_DbTable_Roster_Staffinfo();
		
		$idList = $stInfo->listChanges(Model_DatetimeHelper::dateToday(),Model_DatetimeHelper::dateToday(),'leave');
		
		
		
		
	}
	/**
	 * Add by Norman , According Shop Group and Staff Calcuate Bonus
	 */
	public function calBonusDetailAction(){
		
		$bonus = $this->_getParam("bonus");
		$idGroup = $this->_getParam("id_group");
		$idCycle = $this->_getParam('cycle');
		$groupShops = unserialize(ARR_GROUP_SHOPS);
		$cycles = unserialize(BONUS_CYCLE_2014);
		$dateBegin = $cycles[$idCycle][0];
		$dateEnd = $cycles[$idCycle][1];
		
		$this->view->dateBegin = $dateBegin;
		$this->view->dateEnd = $dateEnd;
		
		$arrShops = $groupShops[$idGroup];
		
		//d($bonus,$dateBegin,$dateEnd,$arrShops);
		
		$ts = new Model_DbTable_Roster_Timesheet();
		
		// calculate Should Paid Hours 
		
		
		
		$amtMgr = round($bonus*0.5,2);
		$amtSc = round($bonus*0.25,2);
		$amtFt = round($bonus*0.25,2);
		
		
		$arrStaff = array();
		foreach($arrShops as $shop){
			
			$tsList = $ts->listConfirmedShiftByDateByShop($shop, $dateBegin, $dateEnd);
			foreach($tsList as $line){
				
				$arrStaff[] = $line['id_staff'];
			}
			
		}
		$arrStaff = array_unique($arrStaff);
		
		//d($arrStaff);
		
		$stInfo = new Model_DbTable_Roster_Staffinfo();
		
		$arrMgr = array();
		$arrSc = array();
		$arrFt = array();
		$arrStName = array();
		
		foreach($arrStaff as $idStaff){
			
			$stLine = $stInfo->getStaffinfo($idStaff);
			
			$arrStName[$idStaff] = $stLine['first_name'].' '.$stLine['last_name'];
			
			if($stLine['position_status'] == 5 || $stLine['position_status'] == 6 ){
				
				$arrMgr[] = $idStaff;
			}
			elseif($stLine['position_status'] == 1 || $stLine['position_status'] == 2 || $stLine['position_status'] == 3   ){
				$arrFt[] = $idStaff;
				
			}
			elseif($stLine['position_status'] == 4){
				$arrSc[] = $idStaff;
			}
			elseif($stLine['position_status'] == 7 || $stLine['position_status'] == 99 || $stLine['position_status'] == 8){
				
			}
			else{
				$arrFt[] = $idStaff;
			}
				
		}
		//d($arrMgr,$arrSc,$arrFt);
		
		//find every singl one total working hours in the group 
		$attRecord = new Model_DbTable_Roster_Attnrecord();
		
		$arrDate = Model_DatetimeHelper::createDateArray($dateBegin, $dateEnd);
		
		$arrWkHr = array();
		
		foreach($arrStaff as $idStaff){
			
			foreach($arrShops as $shop){
				foreach($arrDate as $dateToCheck){
					//find Shift in that
					$shiftLine = $ts->listAllShiftByStaffIdByDateByShop($idStaff, $shop, $dateToCheck, $dateToCheck);
					$attLine = $attRecord->getFirstOnLastOffDuty($idStaff, $dateToCheck,Model_EncryptHelper::sslPassword($shop));
					
					
					foreach($shiftLine as $key => $v){
					
					$firstBreak = 0;
					$breakTime = 1800;
	
					if($v["break_time"]===(int)0 and $v["break_time"]!== null ){
						$breakTime  = 0;
					}
					if((($v["confirm_shift_end"]-$v["confirm_shift_begin"])<18000) && ($v["break_time"] == 0 ||$v["break_time"]== null )){
					
						$breakTime = 0;
					}
					
					if(($v["confirm_shift_end"]-$v["confirm_shift_begin"]) >= 32400){
					
						$firstBreak = 1800;
				
					}
					
					
					$manShiftBegin = $v["confirm_shift_begin"];
					$manShiftEnd = $v["confirm_shift_end"];
					$actBegin = $attLine[0];
					$actEnd = $attLine[1];
					
					$shiftBegin = 0;
					$shiftEnd = 0;
					
					
					$wkHr = 0;
					
					if( $manShiftBegin != null && $manShiftEnd != null && $actBegin != null && $actEnd != null ){
						
						$shiftBegin = ($manShiftBegin > $actBegin)?$manShiftBegin:$actBegin;
						$shiftEnd = ($manShiftEnd < $actEnd)?$manShiftEnd: $actEnd;
						
					}
					
					//d($shiftBegin,$shiftEnd);
					
					$wkHr = $shiftEnd - $shiftBegin - $breakTime - $firstBreak;
					
					if($wkHr >0 ){
						
						if(isset($arrWkHr[$idStaff])){
							$arrWkHr[$idStaff] += round($wkHr/3600,2);
						}
						else{		
							$arrWkHr[$idStaff] = round($wkHr/3600,2);
						}
						
					}
					
					
					
					}
					
					
					
					
				}
				
			}

		}
		
		$this->view->arrMgr = $arrMgr;
		$this->view->arrSc = $arrSc;
		$this->view->arrFt = $arrFt;
		$this->view->arrWkHr = $arrWkHr;
		$this->view->arrStName = $arrStName;
		
		if($_POST){
			//d($_POST);
			
			if(isset($_POST['is_mgr'])){
				
				echo "Manager is ".$arrStName[$_POST['is_mgr']]." will take 50% : ". $bonus ." x  50% = $ ".$amtMgr."<br />"; 
			}
			else{
				
				echo "There is No Manager will Forward 50% :". $bonus ." x  50% = $ ".$amtMgr."<br />";
			}

			if(isset($_POST['is_sc'])){
				
				$scCount = count($_POST['is_sc']);
				$precenter = 1/$scCount;
				foreach($_POST['is_sc'] as $k => $v){
					
					echo "SC is ".$arrStName[$_POST['is_sc'][$k]]." will take ".round($precenter*100,2,PHP_ROUND_HALF_DOWN)."% of 25% : ". $bonus ." x  25% x ".round($precenter*100,2,PHP_ROUND_HALF_DOWN)."%   = $ ".round($amtSc*$precenter,2,PHP_ROUND_HALF_DOWN)."<br />";
					
				}
				
			}
			else{
			
				echo "There is No SC will Forward 25% :". $bonus ." x  25% = $ ".$amtSc."<br />";
			}			
			
			$TotalFullWkHr = array_sum($_POST['is_ft']);
			if(isset($_POST['is_ft'])){
			foreach($_POST['is_ft'] as $k => $v){
				
				echo "Full Time/Part Time Staff: ".$arrStName[$k]." Working Hr : ".$v." hr, is ".round($v/$TotalFullWkHr*100,2,PHP_ROUND_HALF_DOWN)."% Total ".$TotalFullWkHr." hr , Amt is ".$bonus." X 25% x ";
				echo round($v/$TotalFullWkHr*100,2,PHP_ROUND_HALF_DOWN)."% = $ ".round($amtFt * $v/$TotalFullWkHr,2,PHP_ROUND_HALF_DOWN)."<br />";
				
			}
			}
			else{
				
				echo "No Full Time Here Forward That 25%";
			}	
			
			
			
			
		}
		
		//d($arrWkHr);
		
		//find who is working in that time , in those shops 
		// find out who are mangers 
		// find out who are second in charge
		
		
		
		
		
	}
	
	public function importRepairBonusAction(){
		

		$bonus = new Model_Payroll_Staffbonus();
		$stInfo = new Model_DbTable_Roster_Staffinfo();
		
		$fl = fopen("repair.csv","r");
		$cot = 0;
		$db ="";
		$dn = "";
		$payDate="";
		$payDateCash = "";
		$holdDate ="";
		
		while(($lineData = fgetcsv($fl,1024))!=false){
			if($cot >0){
				$amt = $lineData[0];
				
				
				$cashAmt = $amt;
				$bkAmt = round($amt/1.095,2);
				$spBk = $amt - $bkAmt;
				
				$idStaff = $lineData[1];
				if($cot == 1){
					$db = $lineData[2];
					$dn = $lineData[3];
					$payDate = $lineData[5];
					$payDateCash = $lineData[4];
				}
				$actPayDate = "";
				$holdDate = "";
				$payType = 0;
				
				$stLine = $stInfo->getStaffinfo($idStaff);
				$isLeave = ($stLine['leave'] == 9)?"Hold Because Staff Already Leave":"";
				
				if($stLine['id_package'] == 2 || $stLine['id_package'] == 5 ){
					$spBk = 0;
					$bkAmt = 0;
					$payType = 1;
					$actPayDate = $holdDate = $payDateCash;
				}
				else{
					
					$cashAmt= 0;
					$payType = 2;
					$actPayDate = $holdDate = $payDate;
					
					$idBonus = $bonus->findBonus($idStaff, 1, $amt);
					
					//d($idBonus);
					$bonus->updateBankBonus($idBonus, $bkAmt, $spBk);
					echo "Update Bank Bonus ID:".$idBonus." {$bkAmt} , {$spBk}<br />";
				}
				
			//$bonus->addStaffbonus($idStaff,1,"Your Repair Bonus.", $amt, $cashAmt, $bkAmt, $spBk, $db, $dn, $actPayDate, $payType, $holdDate, null,null,null,null,null,null,$isLeave);
				
			}
			$cot++;
		}
	
	

	}
	/**
	 * once off funcion 
	 */
	public function importBankDetailAction(){
		
		$stDetail = new Model_DbTable_Roster_Stafflogindetail();
		$stInfo = new Model_DbTable_Roster_Staffinfo();
		$fl = fopen("ba.csv","r");
		while(($lineData = fgetcsv($fl,2014))!=false){
			
			$arrName = explode(',',$lineData[0]);
			$lastName = strtolower(trim($arrName[0]));
			$firstName = strtolower(trim($arrName[1]));
			
			$stLine = $stDetail->getStaffByName(Model_EncryptHelper::sslPassword($firstName.' '.$lastName));
			if(!$stLine){
				
				echo $lineData[0];
				
			}
			else{
				
				$stID = $stLine[0]['id'];
				
				$stInfo->updateBankDetails($stID,$lineData[2], $lineData[3],$lineData[1]);
				//$stInfo->update
				
			}
			
			
			
			
			
		}	
	}
	public function importTeamBonusAction(){
		
		$bonus = new Model_Payroll_Staffbonus();
		$stInfo = new Model_DbTable_Roster_Staffinfo();
		
		$fl = fopen("group.csv","r");
		
		$cot = 1;
		$db ="2014-03-31";
		$dn = "2014-04-27";
		$payDate="2014-08-07";
		$payDateCash = "2014-08-06";
		$holdDate ="";
		
		while(($lineData = fgetcsv($fl,1024))!=false){
			if($cot >0){
				$amt = $lineData[1];
		
		
				$cashAmt = $amt;
				$bkAmt = round($amt/1.095,2);
				$spBk = $amt - $bkAmt;
		
				$idStaff = $lineData[0];
			
				$actPayDate = "";
				$holdDate = "";
				$payType = 0;
		
				$stLine = $stInfo->getStaffinfo($idStaff);
				$isLeave = ($stLine['leave'] == 9)?"Hold Because Staff Already Leave":"";
		
				if($stLine['id_package'] == 2 || $stLine['id_package'] == 5 ){
					$spBk = 0;
					$bkAmt = 0;
					$payType = 1;
					$actPayDate = $holdDate = $payDateCash;
				}
				else{
						
					$cashAmt= 0;
					$payType = 2;
					$actPayDate = $holdDate = $payDate;
					
					$idBonus = $bonus->findBonus($idStaff, 3, $amt);
						
					//d($idBonus);
					if(!$idBonus){
						
						echo $idBonus." ".$amt;
						
					}
					else{
					$bonus->updateBankBonus($idBonus, $bkAmt, $spBk);
					echo "Update Bank Bonus ID:".$idBonus." {$bkAmt} , {$spBk}<br />";
					}
					
				}
		
				//$bonus->addStaffbonus($idStaff,3,"Your Group Bonus.", $amt, $cashAmt, $bkAmt, $spBk, $db, $dn, $actPayDate, $payType, $holdDate, null,null,null,null,null,null,$isLeave);
		
			}
			$cot++;
		}
		
		
		
	}
	
	public function managerPanelAction(){
		
		$shop = $this->_getParam("shop");
		$this->view->shop = $shop;
		$this->view->checkPass = false;
		$arrMgr = unserialize(ARR_MANAGER);
		
		if($_POST){
			
			$stDetail = new Model_DbTable_Roster_Stafflogindetail();
			$stLine = $stDetail->checkPasswordCorrect(Model_EncryptHelper::hashsha($_POST['password']));
			
			if(!$stLine){
				echo "<h1>The Password You input is Incorrect, Please verify it and try again.</h1>";
			}
			else{
				if(isset($arrMgr[$stLine['id']])){
					
					// it is manager 
					$this->view->checkPass = true;
					$this->view->idMgr = $stLine['id'];
				}
				else{
					echo "<h1>This Link is For Manager Only,You are NOT login as a manager</h1>"; 
					
				}	
				
			}
		}
	}
	
	public function createTaskAction(){
		
		date_default_timezone_set("Australia/Melbourne");
		$dayToday = date("N");
		
		$taskList = new Model_Hr_Tasklist();
		
		
		if($_POST){
			
			$repeatDate = "";
			$repeatMonth = "";
			$repeatWeek = 1;
			$repeatWeekDay = "";
			$repeatCycle = "";
			
			if(isset($_POST['rp_1_day'])){
				$repeatDate = "";
				$repeatMonth = "";
				$repeatWeek = 1;
				$repeatWeekDay = "1,2,3,4,5";
				$repeatCycle = "";
				
			}
			elseif(isset($_POST['rp_wk'])){
				$repeatDate = "";
				$repeatMonth = "";
				$repeatWeek = 1;
				$repeatWeekDay = implode(',', $_POST['rp_wk']);
				$repeatCycle = "";
			}
			elseif(isset($_POST['rp_month'])){
				$repeatDate = trim($_POST['rp_date']);
				$repeatMonth = implode(',', $_POST['rp_month']);
				$repeatWeek = "";
				$repeatWeekDay = "";
				$repeatCycle = "";
			}
			elseif(isset($_POST['rp_cycle'])){
				
				$repeatDate = "";
				$repeatMonth = "";
				$repeatWeek = 1;
				$repeatWeekDay = "";
				$repeatCycle = implode(',', $_POST['rp_cycle']);
				
			}
			
			
			
			if($repeatDate!='' ||  $repeatMonth != '' || $repeatWeekDay !='' || $repeatCycle !=""){
				// did write something insert 
			
				$taskList->addTasklist($_POST['id_staff'], $_POST['task_title'], $_POST['task_comment'], $_POST['task_link'], $repeatMonth, $repeatDate, $repeatWeek, $repeatWeekDay, $repeatCycle, $_POST['email_responsier'],'System',Model_DatetimeHelper::dateToday(),$dayToday);
				
				echo "<h1>Task Created, you May See it in the List</h1>";
			}
			else{
				
				echo "<h1>Missing Information, Task Will Not Create</h1>";
			}
		}
		
		
	}
	public function listAllTaskAction(){
		$task = new Model_Hr_Tasklist();
		$stDetail = new Model_DbTable_Roster_Stafflogindetail();
		
		if($_POST){
			if(isset($_POST['btn_del'])){
				
				$task->deleteTasklist($_POST['id_task']);
			}
			
		}
		
		$taskList = $task->listAll();
		$arrRes = array();
		
		foreach($taskList as $k => $v){
			$tmpArr = $v;

			$id = $v['id_staff'];
			$stLine = $stDetail->getDetail($id);	
			// transfer monthes
			$tmpArr['id_staff'] = ucwords(strtolower($stLine['ni']));
			
			
			$arrRes[] = $tmpArr;
		}
		
		$this->view->taskList = $arrRes;
		
	}
	public function generateTaskAction(){
		
		date_default_timezone_set("Australia/Melbourne");
		// generate Today Task 
		$monthToday = date("m");
		$dateToday = date("d");
		$weekDayToday = date("N");
		$arrCycle2014 = unserialize(BONUS_CYCLE_2014);
		$arrCycle2015 = unserialize(BONUS_CYCLE_2015);
		$date3WeeksAgo = "";
		$fullDate = Model_DatetimeHelper::dateToday();
		
		$trigger = false;
		
		
		if($weekDayToday == 1){
			$date3WeeksAgo = Model_DatetimeHelper::adjustWeeks("sub", $fullDate, 3); // 3 weeks ago
		}
		
		$dateCycle = '';
		
		foreach($arrCycle2014 as $k =>$cv4){
			if($fullDate == $cv4[0]){
				$dateCycle = "begin";
			}
			if($fullDate == $cv4[1]){
				$dateCycle = "end";
			}
			if($date3WeeksAgo == $cv4[0]){
				$dateCycle = "middle";
			}
		}
		
		foreach($arrCycle2015 as $k =>$cv5){
			if($fullDate == $cv5[0]){
				$dateCycle = "begin";
			}
			if($fullDate == $cv5[1]){
				$dateCycle = "end";
			}
			if($date3WeeksAgo == $cv5[0]){
				$dateCycle = "middle";
			}
		}
			
			
		
		$task = new Model_Hr_Tasklist();
		$taskHistory = new Model_Hr_Taskhistory();
		$taskList = $task->listAll();
		
		
		
		
		foreach($taskList as $k => $v){
			$trigger = false;
			//Date of Month
			if(trim($v['repeat_month'])!='' && trim($v['repeat_date']) !=''){

				$arrMonth = explode(",", $v['repeat_month']);
				$arrDate = explode(",",$v['repeat_date']);
				if(in_array($dateToday, $arrDate) && in_array($monthToday, $arrMonth)){
					
					$trigger = true;
				}	
			}
			// Week Day
			if (!$trigger && trim($v['repeat_week_day'])!=""){

				$arrWeekDays = explode(",",$v['repeat_week_day']);
				if(in_array($weekDayToday, $arrWeekDays)){
					
					$trigger = true;
				}
				
			}
			// Cycle 
			if(!$trigger && $dateCycle != ""){
					$trigger = true;
			}
			
			if($trigger){
				$taskHistory->addTaskhistory($v['id_task'],$v['id_staff'],$fullDate,null);
			}
		}
		
		
	}
	/**
	 * Add by norman on 31th
	 */
	public function submitManagerReportAction(){
		$report = new Model_Hr_Manreport();
		
		$manager = base64_decode($this->_getParam("mgr"));
		$shop = $this->_getParam("shop");
		$this->view->shop = $shop;
		$this->view->idManager = $manager;
		$stDetail = new Model_DbTable_Roster_Stafflogindetail();
		$nickName = $stDetail->getDetail($manager);
		$this->view->nickName = ucfirst($nickName['ni']);
		$this->view->message = '';
		
		if($_POST){
			
			$f1Name = '';
			$f2Name = '';
			
			if(isset($_FILES['upload_file_1'])){
				if(move_uploaded_file($_FILES['upload_file_1']['tmp_name'],getcwd()."/import/mreport/".$_FILES['upload_file_1']['name'])){
					$this->view->message .= "upload Attachment File 1 Success<br />";
					$f1Name = "/import/mreport/".$_FILES['upload_file_1']['name'];
				}
				else{
					$this->view->message .= "upload  1 Fail<br />";
				}
				
				
			}
			if(isset($_FILES['upload_file_2'])){
				
				if(move_uploaded_file($_FILES['upload_file_2']['tmp_name'],getcwd()."/import/mreport/".$_FILES['upload_file_2']['name'])){
					$this->view->message .= "upload Attachment File 2 Success<br />";
					$f2Name = "/import/mreport/".$_FILES['upload_file_2']['name'];
				}
				else{
					$this->view->message .= "upload File 2 Fail<br />";
				}
				
			}
			
			$report->addManreport(
					$_POST['date_begin'],
					$_POST['date_end'],//$dateEnd, 
					$_POST['id_manager'],//$idManager,
					$_POST['shop_name'],// $storeName,
					$_POST['store_sales'],// $storeSales,
					$_POST['possible_reason'],// $possibleReason, 
					$_POST['store_performance'],//$storePerformance,
					$_POST['store_maintenance'],// $storeMaintenance,
					$_POST['staff_issue'],// $staffIssue,
					$_POST['promote'],// $promote, 
					$_POST['recruitment'],//$recruitment,
					$_POST['other_issue'],// $otherIssue,
					$f1Name,// $uploadFile1,
					$f2Name,// $uploadFile2,
					Model_DatetimeHelper::dateToday(),// $submitDate,
					Model_DatetimeHelper::timeNow(),// $submitOn,
					null,// $viewBy,
					null// $viewDate
					);
			
			$this->view->message .= "Report Submit Success<br />";
		}
		
		
	}
	public function listMangerReportAction(){
		
		
	}
	
	public function dischargeApplicationAction(){
		
		$this->view->arrShop = unserialize(ARR_SHOP_ACTIVE);
		$this->view->dateToday = Model_DatetimeHelper::dateToday();
		$this->view->date7days = Model_DatetimeHelper::adjustDays("add",Model_DatetimeHelper::dateToday(),7);
		$managerList = unserialize(ARR_MANAGER);
		
		$stDetail = new Model_DbTable_Roster_Stafflogindetail();
		$this->view->stList = $stDetail->listAllActiveStaff();
		$disLog = new Model_Hr_Discharge();
		
		$stinfo = new Model_DbTable_Roster_Staffinfo();
		
		
		if($_POST){
			//d($_POST);
			//check password
			$idMgr = $stDetail->checkPasswordCorrect(Model_EncryptHelper::hashsha(trim($_POST['password_mgr'])));
			if(!$managerList[$idMgr]){	
				echo '<script type="text/javascript">alert("Incorrect Password, Please click Back Button and Try again, Record Can Not Save");</script>';
				echo '<h1>Incorrect Password</h1>';
			}else{
				//password correct
				$dateLastDay = ($_POST['l_type'] == 1)?$_POST['l_date_type_1']:$_POST['l_date_type_2'];
				$strType =  ($_POST['l_type'] == 1)?'Fire on the spot':'Leave with notice';
				$disLog->addDischarge($_POST['staff_name'], $idMgr['id'],Model_DatetimeHelper::dateToday(), $_POST['l_type'],$_POST['l_reason'], $dateLastDay,$_POST['shop_name']);
				
				$mgrLine = $idMgr['ni'];
				$staff = $stDetail->getDetail($_POST['staff_name']);
				$stLine = $staff['ni'];
				
				// update leave status 
				
				$stinfo->updateLeave($_POST['staff_name'],1,$dateLastDay);
				$mail = new Model_Emailshandler();
				
				$mailBody = "Manger ".$mgrLine." has submit an application in shop ".$_POST['shop_name']." , staff ".$stLine." will leave company on date ".$dateLastDay.",type of the leave is :";
				$mailBody .= $strType.", for the following reason :".$_POST['l_reason']." This is just a notice, you do not need to do anything.";
				
				$mail->sendNormalEmail("simon.seop@phonecollection.com.au;office@phonecollection.com.au","Staff Resignation / Discharge Application Has Been Submit", $mailBody);
				
				
				echo '<h1>Record Added Success, date of last day already set to '.$dateLastDay.' , warehouse has been noticed</h1>';
			}
		}
		
	}
	
	public function chooseStaffUploadDocumentAction(){
		
			$stDetail = new Model_DbTable_Roster_Stafflogindetail();
			$this->view->stList = $stDetail->listStaff();
			
			
		if($_POST){
			$password = $_POST['password'];
			$stLine = $stDetail->checkPasswordCorrect(Model_EncryptHelper::hashsha($password));
			
			if($stLine){
				$idManager = $stLine['id'];
				$idStaff = $_POST['id_staff'];
				$this->_redirect("/staff/manager-upload-document/id_staff/".base64_encode($idStaff)."/id_mgr/".base64_encode($idManager));	
			}
			else{
				
				echo "<h1>Incorrect Password , Try Again</h1>";
			}
		}
	}
	
	public function managerUploadDocumentAction(){
		
			$strStaff = $this->_getParam("id_staff");
			$idStaff = '';
			$strManager = $this->_getParam("id_mgr");
			$mail = new Model_Emailshandler();
			if($strManager == ''){
				$idManager = 110;
				
			}
			else{
				$idManager = base64_decode($strManager);
			}
			if($strStaff!=''){
				$idManager = base64_decode($strManager);	
				$idStaff = base64_decode($strStaff);
			}
			
			$cpath = getcwd();
			$pFile = '/personFile/';
			$idDir = $idStaff.'/';
			
			$errorMsg = '';
			
			//check if file Exist 
			$uploadLog = new Model_Hr_Uploadlog();
			$stInfo = new Model_DbTable_Roster_Staffinfo();
			$stDetail = new Model_DbTable_Roster_Stafflogindetail();
			
			$scanStatus = $stInfo->getStaffDocStatus($idStaff);
			
			
			$dlFileName = $idStaff."_driver_license.jpg";
			$psFileName = $idStaff."_passport.jpg";
			$pvFileName = $idStaff."_passport_visa.jpg";
			$stCardFileName = $idStaff."_student_card.jpg";
			$mcCardFileName = $idStaff."_medicare_card.jpg";
			$cdCardFileName = $idStaff."_credit_card.jpg";
			$tfnFileName = $idStaff."_tfn_form.jpg";
			$preFixSignedDoc = "signed_doc_";
			$preFixOtherDoc = "oth_";
			$arrLevelUpload = $scanStatus;
			
			if($_POST){
				
				if(isset($_POST['bank_bsb'][5]) && isset($_POST['bank_acc_no'][5]) && isset($_POST['bank_acc_name'][1]) ){
						$stInfo->updateBankDetails($idStaff,$_POST['bank_bsb'],$_POST['bank_acc_no'],$_POST['bank_acc_name']);
						$stName = $stInfo->getStaffinfo($idStaff);
						$str = "Staff: ".$stName['first_name']." ".$stName['last_name']."<br/>"."Bank Name: ".$_POST['bank_acc_name']."<br/>"."BSB: ".$_POST['bank_bsb']."<br/>"."Bank Act: ".$_POST['bank_acc_no']."<br/>";
						
						$mail->sendNormalEmail('payroll@phonecollection.com.au', "Staff Bank Info Updated", $str);
				}
				
				// update Banking Detail 
				
				
					
					
				if(!file_exists($cpath.$pFile.$idDir)){
					mkdir($cpath.$pFile.$idDir,0777,true);
				}
					
				// all jpg file
				//driver licience
					
				if(isset($_FILES['driver_license'])){
					if(!move_uploaded_file($_FILES['driver_license']['tmp_name'],$cpath.$pFile.$idDir.$dlFileName)){
						$errorMsg .= 'Driver\'s License Image Upload Failed';
					}
					else{
						//begin the log
						$arrLevelUpload[0] = -1;
						$uploadLog->addUploadlog($idManager, $idStaff,"driver license", $dlFileName,$_FILES['driver_license']['name'],Model_DatetimeHelper::dateToday(),Model_DatetimeHelper::dateToday().' '.Model_DatetimeHelper::timeNow());
					}
				}
				//passport
				if(isset($_FILES['passport'])){
					if(!move_uploaded_file($_FILES['passport']['tmp_name'],$cpath.$pFile.$idDir.$psFileName)){
						$errorMsg .= 'Passport Image Uplaod Failed';
					}
					else{
						//begin the log
						$arrLevelUpload[0] = -1;
						$uploadLog->addUploadlog($idManager, $idStaff,"passport", $psFileName,$_FILES['passport']['name'],Model_DatetimeHelper::dateToday(),Model_DatetimeHelper::dateToday().' '.Model_DatetimeHelper::timeNow());
					}
				}
				//visa page
				if(isset($_FILES['passport_visa'])){
					if(!move_uploaded_file($_FILES['passport_visa']['tmp_name'],$cpath.$pFile.$idDir.$pvFileName)){
						$errorMsg .= 'Passport Visa Page Image Uplaod Failed';
					}
					else{
						//begin the log
						$arrLevelUpload[0] = -1;
						$uploadLog->addUploadlog($idManager, $idStaff,"visa page", $pvFileName,$_FILES['passport_visa']['name'],Model_DatetimeHelper::dateToday(),Model_DatetimeHelper::dateToday().' '.Model_DatetimeHelper::timeNow());
					}
				}
					
				//all jpg file
				if(isset($_FILES['student_card'])){
					if(!move_uploaded_file($_FILES['student_card']['tmp_name'],$cpath.$pFile.$idDir.$stCardFileName)){
						$errorMsg .= 'Student Card Image Uplaod Failed';
					}
					else{
						//begin the log
						$arrLevelUpload[1] = -1;
						$uploadLog->addUploadlog($idManager, $idStaff,"student card", $stCardFileName,$_FILES['student_card']['name'],Model_DatetimeHelper::dateToday(),Model_DatetimeHelper::dateToday().' '.Model_DatetimeHelper::timeNow());
					}
				}
				if(isset($_FILES['medicare_card'])){
					if(!move_uploaded_file($_FILES['medicare_card']['tmp_name'],$cpath.$pFile.$idDir.$mcCardFileName)){
						$errorMsg .= 'Medicare Card Image Uplaod Failed';
					}
					else{
						//begin the log
						$arrLevelUpload[1] = -1;
						$uploadLog->addUploadlog($idManager, $idStaff,"medicare card", $mcCardFileName,$_FILES['medicare_card']['name'],Model_DatetimeHelper::dateToday(),Model_DatetimeHelper::dateToday().' '.Model_DatetimeHelper::timeNow());
					}
				}
				if(isset($_FILES['credit_card'])){
					if(!move_uploaded_file($_FILES['credit_card']['tmp_name'],$cpath.$pFile.$idDir.$cdCardFileName)){
						$errorMsg .= 'Credit Card Image Uplaod Failed';
					}
					else{
						//begin the log
						$arrLevelUpload[1] = -1;
						$uploadLog->addUploadlog($idManager, $idStaff,"credit card", $cdCardFileName,$_FILES['credit_card']['name'],Model_DatetimeHelper::dateToday(),Model_DatetimeHelper::dateToday().' '.Model_DatetimeHelper::timeNow());
					}
				}
				
				if(isset($_FILES['tfn_form'])){
					if(!move_uploaded_file($_FILES['tfn_form']['tmp_name'],$cpath.$pFile.$idDir.$tfnFileName)){
						$errorMsg .= 'TFN Form Uplaod Failed';
					}
					else{
						//begin the log
						$arrLevelUpload[1] = -1;
						$uploadLog->addUploadlog($idManager, $idStaff,"TFN Form", $tfnFileName,$_FILES['tfn_form']['name'],Model_DatetimeHelper::dateToday(),Model_DatetimeHelper::dateToday().' '.Model_DatetimeHelper::timeNow());
					}
				}
					
				// signed page (file name)
				if(!move_uploaded_file($_FILES['sign_doc']['tmp_name'],$cpath.$pFile.$idDir.$preFixSignedDoc.$_FILES['sign_doc']['name'])){
					$errorMsg .= 'Staff Signed Document File Uplaod Failed';
				}
				else{
					//begin the log
					$arrLevelUpload[2] = -1;
					$uploadLog->addUploadlog($idManager, $idStaff,"signed document",$preFixSignedDoc.$_FILES['sign_doc']['name'],'',Model_DatetimeHelper::dateToday(),Model_DatetimeHelper::dateToday().' '.Model_DatetimeHelper::timeNow());
				}
					
				// other file
				if(!move_uploaded_file($_FILES['other_file']['tmp_name'],$cpath.$pFile.$idDir.$preFixOtherDoc.$_FILES['other_file']['name'])){
					$errorMsg .= 'Other File Uplaod Failed';
				}
				else{
					//begin the log
					$uploadLog->addUploadlog($idManager, $idStaff,"other document",$preFixOtherDoc.$_FILES['other_file']['name'],$_POST['other_file_comm'],Model_DatetimeHelper::dateToday(),Model_DatetimeHelper::dateToday().' '.Model_DatetimeHelper::timeNow());
				}
			
					$stInfo->updateStatus($idStaff, $arrLevelUpload[0],$arrLevelUpload[1],$arrLevelUpload[2]);
					
					
				if($errorMsg == ''){
					$errorMsg = 'File Upload Success';
				}
					
					
					
			}
			
			$staffName = $stDetail->getDetail($idStaff);
			
			$this->view->scanStatus = $scanStatus = $stInfo->getStaffDocStatus($idStaff);
			$this->view->bankDetail = $stInfo->getStaffinfo($idStaff);
			$this->view->staffName = ucwords($staffName['ni']).'('.Model_EncryptHelper::getSslPassword($staffName['n']).')';
			
			
			$this->view->dlFileExist = file_exists($cpath.$pFile.$idDir.$dlFileName);
			$this->view->psFileExist = file_exists($cpath.$pFile.$idDir.$psFileName);
			$this->view->pvFileExist = file_exists($cpath.$pFile.$idDir.$pvFileName);
			$this->view->stCardFileExist = file_exists($cpath.$pFile.$idDir.$stCardFileName);
			$this->view->mcCardFileExist = file_exists($cpath.$pFile.$idDir.$mcCardFileName);
			$this->view->cdCardFileExist = file_exists($cpath.$pFile.$idDir.$cdCardFileName);
			$this->view->TfnFileExist = file_exists($cpath.$pFile.$idDir.$tfnFileName);
			
			//list all signed doc and other doc 
			$arrFileList  = self::getDirectoryList($cpath.$pFile.$idDir);
			$arrSdoc = array();
			$arrOdoc = array();
			
			foreach($arrFileList as $file){
				
				if(strpos($file,$preFixSignedDoc) !== false){
					
					$arrSdoc[] = $file;
				}
				if(strpos($file,$preFixOtherDoc) !== false){

					$filecomm = $uploadLog->findUploadComm($file,$idStaff);
					$fileVerify = $uploadLog->fileVerifyStatus($file, $idStaff);
					$arrOdoc[] = array($file,$filecomm,$fileVerify);
				}	
			}
			
			$this->view->arrSdoc = $arrSdoc;
			$this->view->arrOdoc = $arrOdoc;
				
	}
	
	public function reArrangeStaffAction(){
		
		$stDetail = new Model_DbTable_Roster_Stafflogindetail();
		$stInfo = new Model_DbTable_Roster_Staffinfo();
		
		$arrMgr = unserialize(ARR_MANAGER);
		$arrMgrList = array();
		foreach($arrMgr as $k => $v){
			$stLine = $stDetail->getDetail($k);
				
			$arrMgrList[$k] = ucwords($stLine['ni']);
		}
		
		$this->view->arrMgrList = $arrMgrList;
		if(isset($_POST['button'])){
			foreach ($_POST['id_manager'] as $k => $v){
				$stInfo->updateManager($k, $v);
				$stf = $stDetail->getDetail($k);
				echo "Add ".$stf['ni']."---> ".$arrMgrList[$v]." Success <br/>";
			}

		}
		
		if(isset($_POST['checkManager'])){
			if(!empty($_POST['check_manager'])){
				if($_POST['check_manager'] != 'all'){
					
					$mList = $stInfo->listStaffByManager($_POST['check_manager']);
					$mNick = $stDetail->getDetail($_POST['check_manager']);

					echo "<br/>";
					echo "Manager:".$mNick['ni']."<br/>";
					foreach ($mList as $k => $v){
						$ni = $stDetail->getDetail($v['id_staff']);
						echo $v['first_name']." ".$v['last_name']."(".$ni['ni'].")<br/>";
					}
				}else{

					$mList = $stInfo->listStaffByManager(0);

					$sortManager = array();
					foreach ($mList as $k => $v){
							$sortManager[$v['id_manger_belong']][] = $v;
					}
					
					foreach ($sortManager as $idManager => $list){
						$mNick = $stDetail->getDetail($idManager);
						echo "<br/>";
						echo "Manager:".$mNick['ni']."<br/>";
						foreach ($list as $k => $v){
							$ni = $stDetail->getDetail($v['id_staff']);
							echo $v['first_name']." ".$v['last_name']."(".$ni['ni'].")<br/>";
						}
					}
				}
			}
		}
		$tmpstfList = $stInfo->listNullManager();
		$stfList = array();
		foreach ($tmpstfList as $k => $v){
			$nick = $stDetail->getDetail($v['id_staff']);
			$stfList[$v['id_staff']] = $v;
			$stfList[$v['id_staff']]['ni'] = $nick['ni'];
		}
		$this->view->stList = $stfList;
		
		
		
		
		
		
		
	}
	
	private static function getDirectoryList ($directory)
	{
	
		// create an array to hold directory list
		$results = array();
	
		// create a handler for the directory
		$handler = opendir($directory);
	
		// open directory and walk through the filenames
		while ($file = readdir($handler)) {
	
			// if file isn't this directory or its parent, add it to the results
			if ($file != "." && $file != "..") {
				$results[] = $file;
			}
	
		}
	
		// tidy up: close the handler
		closedir($handler);
	
		// done!
		return $results;
	
	}
}
?>